<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlguts - Introduction to the Perl API - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlguts">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlguts.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlguts">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlguts">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlguts">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlguts">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlguts">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlguts">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlguts">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlguts">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlguts">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlguts">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlguts">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlguts">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlguts">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlguts">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlguts">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlguts">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlguts">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlguts">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlguts">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlguts">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlguts">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlguts">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlguts">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlguts">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlguts">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlguts">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlguts">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlguts">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlguts">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlguts">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlguts">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlguts">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlguts">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlguts">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlguts">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlguts">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlguts">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlguts">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlguts">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlguts">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlguts">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlguts">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlguts">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlguts">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlguts">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlguts">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlguts">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlguts">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlguts">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlguts">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlguts">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlguts">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlguts">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlguts">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlguts">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlguts">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlguts">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlguts">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlguts">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlguts">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlguts">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlguts">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlguts">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlguts">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlguts">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlguts">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlguts">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlguts">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlguts">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlguts">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlguts">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlguts">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlguts">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlguts">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlguts">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlguts">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlguts">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlguts">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlguts">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlguts">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlguts.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlguts">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlguts">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlguts">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlguts">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlguts">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlguts">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlguts">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlguts">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlguts">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlguts">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlguts">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlguts">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlguts">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlguts">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlguts">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlguts">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlguts">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlguts">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlguts">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlguts">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlguts">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlguts">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlguts">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlguts">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlguts">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlguts">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlguts">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlguts">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlguts">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlguts">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlguts">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlguts">5.35.1</a>
          <a class="dropdown-item active" href="perlguts.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlguts.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlguts.html">perlguts</a>
          <div id="more">
            (<a href="perlguts.txt">source</a>,
            <a href="https://metacpan.org/pod/perlguts">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#DESCRIPTION">DESCRIPTION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Variables">Variables</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Datatypes">Datatypes</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#What-is-an-%22IV%22?">What is an &quot;IV&quot;?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Working-with-SVs">Working with SVs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Offsets">Offsets</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#What&#39;s-Really-Stored-in-an-SV?">What&#39;s Really Stored in an SV?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Working-with-AVs">Working with AVs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Working-with-HVs">Working with HVs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Hash-API-Extensions">Hash API Extensions</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#AVs,-HVs-and-undefined-values">AVs, HVs and undefined values</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#References">References</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Blessed-References-and-Class-Objects">Blessed References and Class Objects</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Creating-New-Variables">Creating New Variables</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Reference-Counts-and-Mortality">Reference Counts and Mortality</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Stashes-and-Globs">Stashes and Globs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#I/O-Handles">I/O Handles</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Double-Typed-SVs">Double-Typed SVs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Read-Only-Values">Read-Only Values</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Copy-on-Write">Copy on Write</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Magic-Variables">Magic Variables</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Assigning-Magic">Assigning Magic</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Magic-Virtual-Tables">Magic Virtual Tables</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Finding-Magic">Finding Magic</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Understanding-the-Magic-of-Tied-Hashes-and-Arrays">Understanding the Magic of Tied Hashes and Arrays</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Localizing-changes">Localizing changes</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Subroutines">Subroutines</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#XSUBs-and-the-Argument-Stack">XSUBs and the Argument Stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Autoloading-with-XSUBs">Autoloading with XSUBs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Calling-Perl-Routines-from-within-C-Programs">Calling Perl Routines from within C Programs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Putting-a-C-value-on-Perl-stack">Putting a C value on Perl stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Scratchpads">Scratchpads</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Scratchpads-and-recursion">Scratchpads and recursion</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Memory-Allocation">Memory Allocation</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Allocation">Allocation</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Reallocation">Reallocation</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Moving">Moving</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#PerlIO">PerlIO</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Compiled-code">Compiled code</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Code-tree">Code tree</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Examining-the-tree">Examining the tree</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Compile-pass-1:-check-routines">Compile pass 1: check routines</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Compile-pass-1a:-constant-folding">Compile pass 1a: constant folding</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Compile-pass-2:-context-propagation">Compile pass 2: context propagation</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Compile-pass-3:-peephole-optimization">Compile pass 3: peephole optimization</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Pluggable-runops">Pluggable runops</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Compile-time-scope-hooks">Compile-time scope hooks</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Examining-internal-data-structures-with-the-dump-functions">Examining internal data structures with the dump functions</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#How-multiple-interpreters-and-concurrency-are-supported">How multiple interpreters and concurrency are supported</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Background-and-PERL_IMPLICIT_CONTEXT">Background and PERL_IMPLICIT_CONTEXT</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#So-what-happened-to-dTHR?">So what happened to dTHR?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#How-do-I-use-all-this-in-extensions?">How do I use all this in extensions?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Should-I-do-anything-special-if-I-call-perl-from-multiple-threads?">Should I do anything special if I call perl from multiple threads?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Future-Plans-and-PERL_IMPLICIT_SYS">Future Plans and PERL_IMPLICIT_SYS</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Internal-Functions">Internal Functions</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Formatted-Printing-of-IVs,-UVs,-and-NVs">Formatted Printing of IVs, UVs, and NVs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Formatted-Printing-of-SVs">Formatted Printing of SVs</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Formatted-Printing-of-Strings">Formatted Printing of Strings</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Formatted-Printing-of-Size_t-and-SSize_t">Formatted Printing of Size_t and SSize_t</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Formatted-Printing-of-Ptrdiff_t,-intmax_t,-short-and-other-special-sizes">Formatted Printing of Ptrdiff_t, intmax_t, short and other special sizes</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Pointer-To-Integer-and-Integer-To-Pointer">Pointer-To-Integer and Integer-To-Pointer</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Exception-Handling">Exception Handling</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Source-Documentation">Source Documentation</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Backwards-compatibility">Backwards compatibility</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Unicode-Support">Unicode Support</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#What-is-Unicode,-anyway?">What is Unicode, anyway?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#How-can-I-recognise-a-UTF-8-string?">How can I recognise a UTF-8 string?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#How-does-UTF-8-represent-Unicode-characters?">How does UTF-8 represent Unicode characters?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#How-does-Perl-store-UTF-8-strings?">How does Perl store UTF-8 strings?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#How-do-I-pass-a-Perl-string-to-a-C-library?">How do I pass a Perl string to a C library?</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#What-about-SvPV,-SvPV_nolen,-etc.?">What about SvPV, SvPV_nolen, etc.?</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#How-do-I-convert-a-string-to-UTF-8?">How do I convert a string to UTF-8?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#How-do-I-compare-strings?">How do I compare strings?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Is-there-anything-else-I-need-to-know?">Is there anything else I need to know?</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Custom-Operators">Custom Operators</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Stacks">Stacks</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Value-Stack">Value Stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Mark-Stack">Mark Stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Temporaries-Stack">Temporaries Stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Save-Stack">Save Stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Scope-Stack">Scope Stack</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Dynamic-Scope-and-the-Context-Stack">Dynamic Scope and the Context Stack</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Introduction-to-the-context-stack">Introduction to the context stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Pushing-contexts">Pushing contexts</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Popping-contexts">Popping contexts</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Redoing-contexts">Redoing contexts</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#Slab-based-operator-allocation">Slab-based operator allocation</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#AUTHORS">AUTHORS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlguts.html#SEE-ALSO">SEE ALSO</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlguts.html#NAME">#</a>NAME</h1>

<p>perlguts - Introduction to the Perl API</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlguts.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>This document attempts to describe how to use the Perl API, as well as to provide some info on the basic workings of the Perl core. It is far from complete and probably contains many errors. Please refer any questions or comments to the author below.</p>

<h1 id="Variables"><a class="permalink" href="perlguts.html#Variables">#</a>Variables</h1>

<h2 id="Datatypes"><a class="permalink" href="perlguts.html#Datatypes">#</a>Datatypes</h2>

<p>Perl has three typedefs that handle Perl&#39;s three main data types:</p>

<pre><code class="plaintext">SV  Scalar Value
AV  Array Value
HV  Hash Value</code></pre>

<p>Each typedef has specific routines that manipulate the various data types.</p>

<h2 id="What-is-an-&quot;IV&quot;?"><a class="permalink" href="perlguts.html#What-is-an-%22IV%22?">#</a><a id="What"></a><a id="What-is-an-IV"></a>What is an &quot;IV&quot;?</h2>

<p>Perl uses a special typedef IV which is a simple signed integer type that is guaranteed to be large enough to hold a pointer (as well as an integer). Additionally, there is the UV, which is simply an unsigned IV.</p>

<p>Perl also uses several special typedefs to declare variables to hold integers of (at least) a given size. Use I8, I16, I32, and I64 to declare a signed integer variable which has at least as many bits as the number in its name. These all evaluate to the native C type that is closest to the given number of bits, but no smaller than that number. For example, on many platforms, a <code>short</code> is 16 bits long, and if so, I16 will evaluate to a <code>short</code>. But on platforms where a <code>short</code> isn&#39;t exactly 16 bits, Perl will use the smallest type that contains 16 bits or more.</p>

<p>U8, U16, U32, and U64 are to declare the corresponding unsigned integer types.</p>

<p>If the platform doesn&#39;t support 64-bit integers, both I64 and U64 will be undefined. Use IV and UV to declare the largest practicable, and <code><a href="perlapi.html#WIDEST_UTYPE">&quot;WIDEST_UTYPE&quot; in perlapi</a></code> for the absolute maximum unsigned, but which may not be usable in all circumstances.</p>

<p>A numeric constant can be specified with <a href="perlapi.html#INT16_C">&quot;<code>INT16_C</code>&quot; in perlapi</a>, <a href="perlapi.html#UINTMAX_C">&quot;<code>UINTMAX_C</code>&quot; in perlapi</a>, and similar.</p>

<h2 id="Working-with-SVs"><a class="permalink" href="perlguts.html#Working-with-SVs">#</a><a id="Working"></a>Working with SVs</h2>

<p>An SV can be created and loaded with one command. There are five types of values that can be loaded: an integer value (IV), an unsigned integer value (UV), a double (NV), a string (PV), and another scalar (SV). (&quot;PV&quot; stands for &quot;Pointer Value&quot;. You might think that it is misnamed because it is described as pointing only to strings. However, it is possible to have it point to other things. For example, it could point to an array of UVs. But, using it for non-strings requires care, as the underlying assumption of much of the internals is that PVs are just for strings. Often, for example, a trailing <code>NUL</code> is tacked on automatically. The non-string use is documented only in this paragraph.)</p>

<p>The seven routines are:</p>

<pre><code>SV*  newSViv(IV);
SV*  newSVuv(UV);
SV*  newSVnv(double);
SV*  newSVpv(const char*, STRLEN);
SV*  newSVpvn(const char*, STRLEN);
SV*  newSVpvf(const char*, ...);
SV*  newSVsv(SV*);</code></pre>

<p><code>STRLEN</code> is an integer type (<code>Size_t</code>, usually defined as <code>size_t</code> in <i>config.h</i>) guaranteed to be large enough to represent the size of any string that perl can handle.</p>

<p>In the unlikely case of a SV requiring more complex initialization, you can create an empty SV with newSV(len). If <code>len</code> is 0 an empty SV of type NULL is returned, else an SV of type PV is returned with len + 1 (for the <code>NUL</code>) bytes of storage allocated, accessible via SvPVX. In both cases the SV has the undef value.</p>

<pre><code class="plaintext">SV *sv = newSV(0);   /* no storage allocated  */
SV *sv = newSV(10);  /* 10 (+1) bytes of uninitialised storage
                      * allocated */</code></pre>

<p>To change the value of an <i>already-existing</i> SV, there are eight routines:</p>

<pre><code>void  sv_setiv(SV*, IV);
void  sv_setuv(SV*, UV);
void  sv_setnv(SV*, double);
void  sv_setpv(SV*, const char*);
void  sv_setpvn(SV*, const char*, STRLEN)
void  sv_setpvf(SV*, const char*, ...);
void  sv_vsetpvfn(SV*, const char*, STRLEN, va_list *,
                                    SV **, Size_t, bool *);
void  sv_setsv(SV*, SV*);</code></pre>

<p>Notice that you can choose to specify the length of the string to be assigned by using <code>sv_setpvn</code>, <code>newSVpvn</code>, or <code>newSVpv</code>, or you may allow Perl to calculate the length by using <code>sv_setpv</code> or by specifying 0 as the second argument to <code>newSVpv</code>. Be warned, though, that Perl will determine the string&#39;s length by using <code>strlen</code>, which depends on the string terminating with a <code>NUL</code> character, and not otherwise containing NULs.</p>

<p>The arguments of <code>sv_setpvf</code> are processed like <code>sprintf</code>, and the formatted output becomes the value.</p>

<p><code>sv_vsetpvfn</code> is an analogue of <code>vsprintf</code>, but it allows you to specify either a pointer to a variable argument list or the address and length of an array of SVs. The last argument points to a boolean; on return, if that boolean is true, then locale-specific information has been used to format the string, and the string&#39;s contents are therefore untrustworthy (see <a href="perlsec.html">perlsec</a>). This pointer may be NULL if that information is not important. Note that this function requires you to specify the length of the format.</p>

<p>The <code>sv_set*()</code> functions are not generic enough to operate on values that have &quot;magic&quot;. See <a href="perlguts.html#Magic-Virtual-Tables">&quot;Magic Virtual Tables&quot;</a> later in this document.</p>

<p>All SVs that contain strings should be terminated with a <code>NUL</code> character. If it is not <code>NUL</code>-terminated there is a risk of core dumps and corruptions from code which passes the string to C functions or system calls which expect a <code>NUL</code>-terminated string. Perl&#39;s own functions typically add a trailing <code>NUL</code> for this reason. Nevertheless, you should be very careful when you pass a string stored in an SV to a C function or system call.</p>

<p>To access the actual value that an SV points to, Perl&#39;s API exposes several macros that coerce the actual scalar type into an IV, UV, double, or string:</p>

<ul>

<li><p><code>SvIV(SV*)</code> (<code>IV</code>) and <code>SvUV(SV*)</code> (<code>UV</code>)</p>

</li>
<li><p><code>SvNV(SV*)</code> (<code>double</code>)</p>

</li>
<li><p>Strings are a bit complicated:</p>

<ul>

<li><p>Byte string: <code>SvPVbyte(SV*, STRLEN len)</code> or <code>SvPVbyte_nolen(SV*)</code></p>

<p>If the Perl string is <code>&quot;\xff\xff&quot;</code>, then this returns a 2-byte <code>char*</code>.</p>

<p>This is suitable for Perl strings that represent bytes.</p>

</li>
<li><p>UTF-8 string: <code>SvPVutf8(SV*, STRLEN len)</code> or <code>SvPVutf8_nolen(SV*)</code></p>

<p>If the Perl string is <code>&quot;\xff\xff&quot;</code>, then this returns a 4-byte <code>char*</code>.</p>

<p>This is suitable for Perl strings that represent characters.</p>

<p><b>CAVEAT</b>: That <code>char*</code> will be encoded via Perl&#39;s internal UTF-8 variant, which means that if the SV contains non-Unicode code points (e.g., 0x110000), then the result may contain extensions over valid UTF-8. See <a href="perlapi.html#is_strict_utf8_string">&quot;is_strict_utf8_string&quot; in perlapi</a> for some methods Perl gives you to check the UTF-8 validity of these macros&#39; returns.</p>

</li>
<li><p>You can also use <code>SvPV(SV*, STRLEN len)</code> or <code>SvPV_nolen(SV*)</code> to fetch the SV&#39;s raw internal buffer. This is tricky, though; if your Perl string is <code>&quot;\xff\xff&quot;</code>, then depending on the SV&#39;s internal encoding you might get back a 2-byte <b>OR</b> a 4-byte <code>char*</code>. Moreover, if it&#39;s the 4-byte string, that could come from either Perl <code>&quot;\xff\xff&quot;</code> stored UTF-8 encoded, or Perl <code>&quot;\xc3\xbf\xc3\xbf&quot;</code> stored as raw octets. To differentiate between these you <b>MUST</b> look up the SV&#39;s UTF8 bit (cf. <code>SvUTF8</code>) to know whether the source Perl string is 2 characters (<code>SvUTF8</code> would be on) or 4 characters (<code>SvUTF8</code> would be off).</p>

<p><b>IMPORTANT:</b> Use of <code>SvPV</code>, <code>SvPV_nolen</code>, or similarly-named macros <i>without</i> looking up the SV&#39;s UTF8 bit is almost certainly a bug if non-ASCII input is allowed.</p>

<p>When the UTF8 bit is on, the same <b>CAVEAT</b> about UTF-8 validity applies here as for <code>SvPVutf8</code>.</p>

</li>
</ul>

<p>(See <a href="perlguts.html#How-do-I-pass-a-Perl-string-to-a-C-library%3F">&quot;How do I pass a Perl string to a C library?&quot;</a> for more details.)</p>

<p>In <code>SvPVbyte</code>, <code>SvPVutf8</code>, and <code>SvPV</code>, the length of the <code>char*</code> returned is placed into the variable <code>len</code> (these are macros, so you do <i>not</i> use <code>&amp;len</code>). If you do not care what the length of the data is, use <code>SvPVbyte_nolen</code>, <code>SvPVutf8_nolen</code>, or <code>SvPV_nolen</code> instead. The global variable <code>PL_na</code> can also be given to <code>SvPVbyte</code>/<code>SvPVutf8</code>/<code>SvPV</code> in this case. But that can be quite inefficient because <code>PL_na</code> must be accessed in thread-local storage in threaded Perl. In any case, remember that Perl allows arbitrary strings of data that may both contain NULs and might not be terminated by a <code>NUL</code>.</p>

<p>Also remember that C doesn&#39;t allow you to safely say <code>foo(SvPVbyte(s, len), len);</code>. It might work with your compiler, but it won&#39;t work for everyone. Break this sort of statement up into separate assignments:</p>

<pre><code>SV *s;
STRLEN len;
char *ptr;
ptr = SvPVbyte(s, len);
foo(ptr, len);</code></pre>

</li>
</ul>

<p>If you want to know if the scalar value is TRUE, you can use:</p>

<pre><code class="plaintext">SvTRUE(SV*)</code></pre>

<p>Although Perl will automatically grow strings for you, if you need to force Perl to allocate more memory for your SV, you can use the macro</p>

<pre><code class="plaintext">SvGROW(SV*, STRLEN newlen)</code></pre>

<p>which will determine if more memory needs to be allocated. If so, it will call the function <code>sv_grow</code>. Note that <code>SvGROW</code> can only increase, not decrease, the allocated memory of an SV and that it does not automatically add space for the trailing <code>NUL</code> byte (perl&#39;s own string functions typically do <code>SvGROW(sv, len + 1)</code>).</p>

<p>If you want to write to an existing SV&#39;s buffer and set its value to a string, use SvPVbyte_force() or one of its variants to force the SV to be a PV. This will remove any of various types of non-stringness from the SV while preserving the content of the SV in the PV. This can be used, for example, to append data from an API function to a buffer without extra copying:</p>

<pre><code>(void)SvPVbyte_force(sv, len);
s = SvGROW(sv, len + needlen + 1);
/* something that modifies up to needlen bytes at s+len, but
   modifies newlen bytes
     eg. newlen = read(fd, s + len, needlen);
   ignoring errors for these examples
 */
s[len + newlen] = &#39;\0&#39;;
SvCUR_set(sv, len + newlen);
SvUTF8_off(sv);
SvSETMAGIC(sv);</code></pre>

<p>If you already have the data in memory or if you want to keep your code simple, you can use one of the sv_cat*() variants, such as sv_catpvn(). If you want to insert anywhere in the string you can use sv_insert() or sv_insert_flags().</p>

<p>If you don&#39;t need the existing content of the SV, you can avoid some copying with:</p>

<pre><code>SvPVCLEAR(sv);
s = SvGROW(sv, needlen + 1);
/* something that modifies up to needlen bytes at s, but modifies
   newlen bytes
     eg. newlen = read(fd, s, needlen);
 */
s[newlen] = &#39;\0&#39;;
SvCUR_set(sv, newlen);
SvPOK_only(sv); /* also clears SVf_UTF8 */
SvSETMAGIC(sv);</code></pre>

<p>Again, if you already have the data in memory or want to avoid the complexity of the above, you can use sv_setpvn().</p>

<p>If you have a buffer allocated with Newx() and want to set that as the SV&#39;s value, you can use sv_usepvn_flags(). That has some requirements if you want to avoid perl re-allocating the buffer to fit the trailing NUL:</p>

<pre><code>Newx(buf, somesize+1, char);
/* ... fill in buf ... */
buf[somesize] = &#39;\0&#39;;
sv_usepvn_flags(sv, buf, somesize, SV_SMAGIC | SV_HAS_TRAILING_NUL);
/* buf now belongs to perl, don&#39;t release it */</code></pre>

<p>If you have an SV and want to know what kind of data Perl thinks is stored in it, you can use the following macros to check the type of SV you have.</p>

<pre><code class="plaintext">SvIOK(SV*)
SvNOK(SV*)
SvPOK(SV*)</code></pre>

<p>You can get and set the current length of the string stored in an SV with the following macros:</p>

<pre><code class="plaintext">SvCUR(SV*)
SvCUR_set(SV*, I32 val)</code></pre>

<p>You can also get a pointer to the end of the string stored in the SV with the macro:</p>

<pre><code class="plaintext">SvEND(SV*)</code></pre>

<p>But note that these last three macros are valid only if <code>SvPOK()</code> is true.</p>

<p>If you want to append something to the end of string stored in an <code>SV*</code>, you can use the following functions:</p>

<pre><code>void  sv_catpv(SV*, const char*);
void  sv_catpvn(SV*, const char*, STRLEN);
void  sv_catpvf(SV*, const char*, ...);
void  sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **,
                                                         I32, bool);
void  sv_catsv(SV*, SV*);</code></pre>

<p>The first function calculates the length of the string to be appended by using <code>strlen</code>. In the second, you specify the length of the string yourself. The third function processes its arguments like <code>sprintf</code> and appends the formatted output. The fourth function works like <code>vsprintf</code>. You can specify the address and length of an array of SVs instead of the va_list argument. The fifth function extends the string stored in the first SV with the string stored in the second SV. It also forces the second SV to be interpreted as a string.</p>

<p>The <code>sv_cat*()</code> functions are not generic enough to operate on values that have &quot;magic&quot;. See <a href="perlguts.html#Magic-Virtual-Tables">&quot;Magic Virtual Tables&quot;</a> later in this document.</p>

<p>If you know the name of a scalar variable, you can get a pointer to its SV by using the following:</p>

<pre><code>SV*  get_sv(&quot;package::varname&quot;, 0);</code></pre>

<p>This returns NULL if the variable does not exist.</p>

<p>If you want to know if this variable (or any other SV) is actually <code>defined</code>, you can call:</p>

<pre><code class="plaintext">SvOK(SV*)</code></pre>

<p>The scalar <code>undef</code> value is stored in an SV instance called <code>PL_sv_undef</code>.</p>

<p>Its address can be used whenever an <code>SV*</code> is needed. Make sure that you don&#39;t try to compare a random sv with <code>&amp;PL_sv_undef</code>. For example when interfacing Perl code, it&#39;ll work correctly for:</p>

<pre><code>foo(undef);</code></pre>

<p>But won&#39;t work when called as:</p>

<pre><code>$x = undef;
foo($x);</code></pre>

<p>So to repeat always use SvOK() to check whether an sv is defined.</p>

<p>Also you have to be careful when using <code>&amp;PL_sv_undef</code> as a value in AVs or HVs (see <a href="perlguts.html#AVs%2C-HVs-and-undefined-values">&quot;AVs, HVs and undefined values&quot;</a>).</p>

<p>There are also the two values <code>PL_sv_yes</code> and <code>PL_sv_no</code>, which contain boolean TRUE and FALSE values, respectively. Like <code>PL_sv_undef</code>, their addresses can be used whenever an <code>SV*</code> is needed.</p>

<p>Do not be fooled into thinking that <code>(SV *) 0</code> is the same as <code>&amp;PL_sv_undef</code>. Take this code:</p>

<pre><code>SV* sv = (SV*) 0;
if (I-am-to-return-a-real-value) {
        sv = sv_2mortal(newSViv(42));
}
sv_setsv(ST(0), sv);</code></pre>

<p>This code tries to return a new SV (which contains the value 42) if it should return a real value, or undef otherwise. Instead it has returned a NULL pointer which, somewhere down the line, will cause a segmentation violation, bus error, or just weird results. Change the zero to <code>&amp;PL_sv_undef</code> in the first line and all will be well.</p>

<p>To free an SV that you&#39;ve created, call <code>SvREFCNT_dec(SV*)</code>. Normally this call is not necessary (see <a href="perlguts.html#Reference-Counts-and-Mortality">&quot;Reference Counts and Mortality&quot;</a>).</p>

<h2 id="Offsets"><a class="permalink" href="perlguts.html#Offsets">#</a>Offsets</h2>

<p>Perl provides the function <code>sv_chop</code> to efficiently remove characters from the beginning of a string; you give it an SV and a pointer to somewhere inside the PV, and it discards everything before the pointer. The efficiency comes by means of a little hack: instead of actually removing the characters, <code>sv_chop</code> sets the flag <code>OOK</code> (offset OK) to signal to other functions that the offset hack is in effect, and it moves the PV pointer (called <code>SvPVX</code>) forward by the number of bytes chopped off, and adjusts <code>SvCUR</code> and <code>SvLEN</code> accordingly. (A portion of the space between the old and new PV pointers is used to store the count of chopped bytes.)</p>

<p>Hence, at this point, the start of the buffer that we allocated lives at <code>SvPVX(sv) - SvIV(sv)</code> in memory and the PV pointer is pointing into the middle of this allocated storage.</p>

<p>This is best demonstrated by example. Normally copy-on-write will prevent the substitution from operator from using this hack, but if you can craft a string for which copy-on-write is not possible, you can see it in play. In the current implementation, the final byte of a string buffer is used as a copy-on-write reference count. If the buffer is not big enough, then copy-on-write is skipped. First have a look at an empty string:</p>

<pre><code>% ./perl -Ilib -MDevel::Peek -le &#39;$a=&quot;&quot;; $a .= &quot;&quot;; Dump $a&#39;
SV = PV(0x7ffb7c008a70) at 0x7ffb7c030390
  REFCNT = 1
  FLAGS = (POK,pPOK)
  PV = 0x7ffb7bc05b50 &quot;&quot;\0
  CUR = 0
  LEN = 10</code></pre>

<p>Notice here the LEN is 10. (It may differ on your platform.) Extend the length of the string to one less than 10, and do a substitution:</p>

<pre><code>% ./perl -Ilib -MDevel::Peek -le &#39;$a=&quot;&quot;; $a.=&quot;123456789&quot;; $a=~s/.//; \
                                                           Dump($a)&#39;
SV = PV(0x7ffa04008a70) at 0x7ffa04030390
  REFCNT = 1
  FLAGS = (POK,OOK,pPOK)
  OFFSET = 1
  PV = 0x7ffa03c05b61 ( &quot;\1&quot; . ) &quot;23456789&quot;\0
  CUR = 8
  LEN = 9</code></pre>

<p>Here the number of bytes chopped off (1) is shown next as the OFFSET. The portion of the string between the &quot;real&quot; and the &quot;fake&quot; beginnings is shown in parentheses, and the values of <code>SvCUR</code> and <code>SvLEN</code> reflect the fake beginning, not the real one. (The first character of the string buffer happens to have changed to &quot;\1&quot; here, not &quot;1&quot;, because the current implementation stores the offset count in the string buffer. This is subject to change.)</p>

<p>Something similar to the offset hack is performed on AVs to enable efficient shifting and splicing off the beginning of the array; while <code>AvARRAY</code> points to the first element in the array that is visible from Perl, <code>AvALLOC</code> points to the real start of the C array. These are usually the same, but a <code>shift</code> operation can be carried out by increasing <code>AvARRAY</code> by one and decreasing <code>AvFILL</code> and <code>AvMAX</code>. Again, the location of the real start of the C array only comes into play when freeing the array. See <code>av_shift</code> in <i>av.c</i>.</p>

<h2 id="What&#39;s-Really-Stored-in-an-SV?"><a class="permalink" href="perlguts.html#What&#39;s-Really-Stored-in-an-SV?">#</a><a id="What1"></a><a id="Whats-Really-Stored-in-an-SV"></a>What&#39;s Really Stored in an SV?</h2>

<p>Recall that the usual method of determining the type of scalar you have is to use <code>Sv*OK</code> macros. Because a scalar can be both a number and a string, usually these macros will always return TRUE and calling the <code>Sv*V</code> macros will do the appropriate conversion of string to integer/double or integer/double to string.</p>

<p>If you <i>really</i> need to know if you have an integer, double, or string pointer in an SV, you can use the following three macros instead:</p>

<pre><code class="plaintext">SvIOKp(SV*)
SvNOKp(SV*)
SvPOKp(SV*)</code></pre>

<p>These will tell you if you truly have an integer, double, or string pointer stored in your SV. The &quot;p&quot; stands for private.</p>

<p>There are various ways in which the private and public flags may differ. For example, in perl 5.16 and earlier a tied SV may have a valid underlying value in the IV slot (so SvIOKp is true), but the data should be accessed via the FETCH routine rather than directly, so SvIOK is false. (In perl 5.18 onwards, tied scalars use the flags the same way as untied scalars.) Another is when numeric conversion has occurred and precision has been lost: only the private flag is set on &#39;lossy&#39; values. So when an NV is converted to an IV with loss, SvIOKp, SvNOKp and SvNOK will be set, while SvIOK wont be.</p>

<p>In general, though, it&#39;s best to use the <code>Sv*V</code> macros.</p>

<h2 id="Working-with-AVs"><a class="permalink" href="perlguts.html#Working-with-AVs">#</a><a id="Working1"></a>Working with AVs</h2>

<p>There are two ways to create and load an AV. The first method creates an empty AV:</p>

<pre><code>AV*  newAV();</code></pre>

<p>The second method both creates the AV and initially populates it with SVs:</p>

<pre><code>AV*  av_make(SSize_t num, SV **ptr);</code></pre>

<p>The second argument points to an array containing <code>num</code> <code>SV*</code>&#39;s. Once the AV has been created, the SVs can be destroyed, if so desired.</p>

<p>Once the AV has been created, the following operations are possible on it:</p>

<pre><code>void  av_push(AV*, SV*);
SV*   av_pop(AV*);
SV*   av_shift(AV*);
void  av_unshift(AV*, SSize_t num);</code></pre>

<p>These should be familiar operations, with the exception of <code>av_unshift</code>. This routine adds <code>num</code> elements at the front of the array with the <code>undef</code> value. You must then use <code>av_store</code> (described below) to assign values to these new elements.</p>

<p>Here are some other functions:</p>

<pre><code>SSize_t av_top_index(AV*);
SV**    av_fetch(AV*, SSize_t key, I32 lval);
SV**    av_store(AV*, SSize_t key, SV* val);</code></pre>

<p>The <code>av_top_index</code> function returns the highest index value in an array (just like $#array in Perl). If the array is empty, -1 is returned. The <code>av_fetch</code> function returns the value at index <code>key</code>, but if <code>lval</code> is non-zero, then <code>av_fetch</code> will store an undef value at that index. The <code>av_store</code> function stores the value <code>val</code> at index <code>key</code>, and does not increment the reference count of <code>val</code>. Thus the caller is responsible for taking care of that, and if <code>av_store</code> returns NULL, the caller will have to decrement the reference count to avoid a memory leak. Note that <code>av_fetch</code> and <code>av_store</code> both return <code>SV**</code>&#39;s, not <code>SV*</code>&#39;s as their return value.</p>

<p>A few more:</p>

<pre><code>void  av_clear(AV*);
void  av_undef(AV*);
void  av_extend(AV*, SSize_t key);</code></pre>

<p>The <code>av_clear</code> function deletes all the elements in the AV* array, but does not actually delete the array itself. The <code>av_undef</code> function will delete all the elements in the array plus the array itself. The <code>av_extend</code> function extends the array so that it contains at least <code>key+1</code> elements. If <code>key+1</code> is less than the currently allocated length of the array, then nothing is done.</p>

<p>If you know the name of an array variable, you can get a pointer to its AV by using the following:</p>

<pre><code>AV*  get_av(&quot;package::varname&quot;, 0);</code></pre>

<p>This returns NULL if the variable does not exist.</p>

<p>See <a href="perlguts.html#Understanding-the-Magic-of-Tied-Hashes-and-Arrays">&quot;Understanding the Magic of Tied Hashes and Arrays&quot;</a> for more information on how to use the array access functions on tied arrays.</p>

<h2 id="Working-with-HVs"><a class="permalink" href="perlguts.html#Working-with-HVs">#</a><a id="Working2"></a>Working with HVs</h2>

<p>To create an HV, you use the following routine:</p>

<pre><code>HV*  newHV();</code></pre>

<p>Once the HV has been created, the following operations are possible on it:</p>

<pre><code>SV**  hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
SV**  hv_fetch(HV*, const char* key, U32 klen, I32 lval);</code></pre>

<p>The <code>klen</code> parameter is the length of the key being passed in (Note that you cannot pass 0 in as a value of <code>klen</code> to tell Perl to measure the length of the key). The <code>val</code> argument contains the SV pointer to the scalar being stored, and <code>hash</code> is the precomputed hash value (zero if you want <code>hv_store</code> to calculate it for you). The <code>lval</code> parameter indicates whether this fetch is actually a part of a store operation, in which case a new undefined value will be added to the HV with the supplied key and <code>hv_fetch</code> will return as if the value had already existed.</p>

<p>Remember that <code>hv_store</code> and <code>hv_fetch</code> return <code>SV**</code>&#39;s and not just <code>SV*</code>. To access the scalar value, you must first dereference the return value. However, you should check to make sure that the return value is not NULL before dereferencing it.</p>

<p>The first of these two functions checks if a hash table entry exists, and the second deletes it.</p>

<pre><code>bool  hv_exists(HV*, const char* key, U32 klen);
SV*   hv_delete(HV*, const char* key, U32 klen, I32 flags);</code></pre>

<p>If <code>flags</code> does not include the <code>G_DISCARD</code> flag then <code>hv_delete</code> will create and return a mortal copy of the deleted value.</p>

<p>And more miscellaneous functions:</p>

<pre><code>void   hv_clear(HV*);
void   hv_undef(HV*);</code></pre>

<p>Like their AV counterparts, <code>hv_clear</code> deletes all the entries in the hash table but does not actually delete the hash table. The <code>hv_undef</code> deletes both the entries and the hash table itself.</p>

<p>Perl keeps the actual data in a linked list of structures with a typedef of HE. These contain the actual key and value pointers (plus extra administrative overhead). The key is a string pointer; the value is an <code>SV*</code>. However, once you have an <code>HE*</code>, to get the actual key and value, use the routines specified below.</p>

<pre><code>    I32    hv_iterinit(HV*);
            /* Prepares starting point to traverse hash table */
    HE*    hv_iternext(HV*);
            /* Get the next entry, and return a pointer to a
               structure that has both the key and value */
    char*  hv_iterkey(HE* entry, I32* retlen);
            /* Get the key from an HE structure and also return
               the length of the key string */
    SV*    hv_iterval(HV*, HE* entry);
            /* Return an SV pointer to the value of the HE
               structure */
    SV*    hv_iternextsv(HV*, char** key, I32* retlen);
            /* This convenience routine combines hv_iternext,
	       hv_iterkey, and hv_iterval.  The key and retlen
	       arguments are return values for the key and its
	       length.  The value is returned in the SV* argument */</code></pre>

<p>If you know the name of a hash variable, you can get a pointer to its HV by using the following:</p>

<pre><code>HV*  get_hv(&quot;package::varname&quot;, 0);</code></pre>

<p>This returns NULL if the variable does not exist.</p>

<p>The hash algorithm is defined in the <code>PERL_HASH</code> macro:</p>

<pre><code class="plaintext">PERL_HASH(hash, key, klen)</code></pre>

<p>The exact implementation of this macro varies by architecture and version of perl, and the return value may change per invocation, so the value is only valid for the duration of a single perl process.</p>

<p>See <a href="perlguts.html#Understanding-the-Magic-of-Tied-Hashes-and-Arrays">&quot;Understanding the Magic of Tied Hashes and Arrays&quot;</a> for more information on how to use the hash access functions on tied hashes.</p>

<h2 id="Hash-API-Extensions"><a class="permalink" href="perlguts.html#Hash-API-Extensions">#</a><a id="Hash"></a>Hash API Extensions</h2>

<p>Beginning with version 5.004, the following functions are also supported:</p>

<pre><code>HE*     hv_fetch_ent  (HV* tb, SV* key, I32 lval, U32 hash);
HE*     hv_store_ent  (HV* tb, SV* key, SV* val, U32 hash);

bool    hv_exists_ent (HV* tb, SV* key, U32 hash);
SV*     hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);

SV*     hv_iterkeysv  (HE* entry);</code></pre>

<p>Note that these functions take <code>SV*</code> keys, which simplifies writing of extension code that deals with hash structures. These functions also allow passing of <code>SV*</code> keys to <code>tie</code> functions without forcing you to stringify the keys (unlike the previous set of functions).</p>

<p>They also return and accept whole hash entries (<code>HE*</code>), making their use more efficient (since the hash number for a particular string doesn&#39;t have to be recomputed every time). See <a href="perlapi.html">perlapi</a> for detailed descriptions.</p>

<p>The following macros must always be used to access the contents of hash entries. Note that the arguments to these macros must be simple variables, since they may get evaluated more than once. See <a href="perlapi.html">perlapi</a> for detailed descriptions of these macros.</p>

<pre><code class="plaintext">HePV(HE* he, STRLEN len)
HeVAL(HE* he)
HeHASH(HE* he)
HeSVKEY(HE* he)
HeSVKEY_force(HE* he)
HeSVKEY_set(HE* he, SV* sv)</code></pre>

<p>These two lower level macros are defined, but must only be used when dealing with keys that are not <code>SV*</code>s:</p>

<pre><code class="plaintext">HeKEY(HE* he)
HeKLEN(HE* he)</code></pre>

<p>Note that both <code>hv_store</code> and <code>hv_store_ent</code> do not increment the reference count of the stored <code>val</code>, which is the caller&#39;s responsibility. If these functions return a NULL value, the caller will usually have to decrement the reference count of <code>val</code> to avoid a memory leak.</p>

<h2 id="AVs,-HVs-and-undefined-values"><a class="permalink" href="perlguts.html#AVs,-HVs-and-undefined-values">#</a><a id="AVs"></a><a id="AVs-HVs-and-undefined-values"></a>AVs, HVs and undefined values</h2>

<p>Sometimes you have to store undefined values in AVs or HVs. Although this may be a rare case, it can be tricky. That&#39;s because you&#39;re used to using <code>&amp;PL_sv_undef</code> if you need an undefined SV.</p>

<p>For example, intuition tells you that this XS code:</p>

<pre><code>AV *av = newAV();
av_store( av, 0, &amp;PL_sv_undef );</code></pre>

<p>is equivalent to this Perl code:</p>

<pre><code>my @av;
$av[0] = undef;</code></pre>

<p>Unfortunately, this isn&#39;t true. In perl 5.18 and earlier, AVs use <code>&amp;PL_sv_undef</code> as a marker for indicating that an array element has not yet been initialized. Thus, <code>exists $av[0]</code> would be true for the above Perl code, but false for the array generated by the XS code. In perl 5.20, storing &amp;PL_sv_undef will create a read-only element, because the scalar &amp;PL_sv_undef itself is stored, not a copy.</p>

<p>Similar problems can occur when storing <code>&amp;PL_sv_undef</code> in HVs:</p>

<pre><code>hv_store( hv, &quot;key&quot;, 3, &amp;PL_sv_undef, 0 );</code></pre>

<p>This will indeed make the value <code>undef</code>, but if you try to modify the value of <code>key</code>, you&#39;ll get the following error:</p>

<pre><code class="plaintext">Modification of non-creatable hash value attempted</code></pre>

<p>In perl 5.8.0, <code>&amp;PL_sv_undef</code> was also used to mark placeholders in restricted hashes. This caused such hash entries not to appear when iterating over the hash or when checking for the keys with the <code>hv_exists</code> function.</p>

<p>You can run into similar problems when you store <code>&amp;PL_sv_yes</code> or <code>&amp;PL_sv_no</code> into AVs or HVs. Trying to modify such elements will give you the following error:</p>

<pre><code class="plaintext">Modification of a read-only value attempted</code></pre>

<p>To make a long story short, you can use the special variables <code>&amp;PL_sv_undef</code>, <code>&amp;PL_sv_yes</code> and <code>&amp;PL_sv_no</code> with AVs and HVs, but you have to make sure you know what you&#39;re doing.</p>

<p>Generally, if you want to store an undefined value in an AV or HV, you should not use <code>&amp;PL_sv_undef</code>, but rather create a new undefined value using the <code>newSV</code> function, for example:</p>

<pre><code>av_store( av, 42, newSV(0) );
hv_store( hv, &quot;foo&quot;, 3, newSV(0), 0 );</code></pre>

<h2 id="References"><a class="permalink" href="perlguts.html#References">#</a>References</h2>

<p>References are a special type of scalar that point to other data types (including other references).</p>

<p>To create a reference, use either of the following functions:</p>

<pre><code>SV* newRV_inc((SV*) thing);
SV* newRV_noinc((SV*) thing);</code></pre>

<p>The <code>thing</code> argument can be any of an <code>SV*</code>, <code>AV*</code>, or <code>HV*</code>. The functions are identical except that <code>newRV_inc</code> increments the reference count of the <code>thing</code>, while <code>newRV_noinc</code> does not. For historical reasons, <code>newRV</code> is a synonym for <code>newRV_inc</code>.</p>

<p>Once you have a reference, you can use the following macro to dereference the reference:</p>

<pre><code class="plaintext">SvRV(SV*)</code></pre>

<p>then call the appropriate routines, casting the returned <code>SV*</code> to either an <code>AV*</code> or <code>HV*</code>, if required.</p>

<p>To determine if an SV is a reference, you can use the following macro:</p>

<pre><code class="plaintext">SvROK(SV*)</code></pre>

<p>To discover what type of value the reference refers to, use the following macro and then check the return value.</p>

<pre><code class="plaintext">SvTYPE(SvRV(SV*))</code></pre>

<p>The most useful types that will be returned are:</p>

<pre><code class="plaintext">SVt_PVAV    Array
SVt_PVHV    Hash
SVt_PVCV    Code
SVt_PVGV    Glob (possibly a file handle)</code></pre>

<p>Any numerical value returned which is less than SVt_PVAV will be a scalar of some form.</p>

<p>See <a href="perlapi.html#svtype">&quot;svtype&quot; in perlapi</a> for more details.</p>

<h2 id="Blessed-References-and-Class-Objects"><a class="permalink" href="perlguts.html#Blessed-References-and-Class-Objects">#</a><a id="Blessed"></a>Blessed References and Class Objects</h2>

<p>References are also used to support object-oriented programming. In perl&#39;s OO lexicon, an object is simply a reference that has been blessed into a package (or class). Once blessed, the programmer may now use the reference to access the various methods in the class.</p>

<p>A reference can be blessed into a package with the following function:</p>

<pre><code>SV* sv_bless(SV* sv, HV* stash);</code></pre>

<p>The <code>sv</code> argument must be a reference value. The <code>stash</code> argument specifies which class the reference will belong to. See <a href="perlguts.html#Stashes-and-Globs">&quot;Stashes and Globs&quot;</a> for information on converting class names into stashes.</p>

<p>/* Still under construction */</p>

<p>The following function upgrades rv to reference if not already one. Creates a new SV for rv to point to. If <code>classname</code> is non-null, the SV is blessed into the specified class. SV is returned.</p>

<pre><code>SV* newSVrv(SV* rv, const char* classname);</code></pre>

<p>The following three functions copy integer, unsigned integer or double into an SV whose reference is <code>rv</code>. SV is blessed if <code>classname</code> is non-null.</p>

<pre><code>SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
SV* sv_setref_uv(SV* rv, const char* classname, UV uv);
SV* sv_setref_nv(SV* rv, const char* classname, NV iv);</code></pre>

<p>The following function copies the pointer value (<i>the address, not the string!</i>) into an SV whose reference is rv. SV is blessed if <code>classname</code> is non-null.</p>

<pre><code>SV* sv_setref_pv(SV* rv, const char* classname, void* pv);</code></pre>

<p>The following function copies a string into an SV whose reference is <code>rv</code>. Set length to 0 to let Perl calculate the string length. SV is blessed if <code>classname</code> is non-null.</p>

<pre><code>SV* sv_setref_pvn(SV* rv, const char* classname, char* pv,
                                                     STRLEN length);</code></pre>

<p>The following function tests whether the SV is blessed into the specified class. It does not check inheritance relationships.</p>

<pre><code>int  sv_isa(SV* sv, const char* name);</code></pre>

<p>The following function tests whether the SV is a reference to a blessed object.</p>

<pre><code>int  sv_isobject(SV* sv);</code></pre>

<p>The following function tests whether the SV is derived from the specified class. SV can be either a reference to a blessed object or a string containing a class name. This is the function implementing the <code>UNIVERSAL::isa</code> functionality.</p>

<pre><code>bool sv_derived_from(SV* sv, const char* name);</code></pre>

<p>To check if you&#39;ve got an object derived from a specific class you have to write:</p>

<pre><code class="plaintext">if (sv_isobject(sv) &amp;&amp; sv_derived_from(sv, class)) { ... }</code></pre>

<h2 id="Creating-New-Variables"><a class="permalink" href="perlguts.html#Creating-New-Variables">#</a><a id="Creating"></a>Creating New Variables</h2>

<p>To create a new Perl variable with an undef value which can be accessed from your Perl script, use the following routines, depending on the variable type.</p>

<pre><code>SV*  get_sv(&quot;package::varname&quot;, GV_ADD);
AV*  get_av(&quot;package::varname&quot;, GV_ADD);
HV*  get_hv(&quot;package::varname&quot;, GV_ADD);</code></pre>

<p>Notice the use of GV_ADD as the second parameter. The new variable can now be set, using the routines appropriate to the data type.</p>

<p>There are additional macros whose values may be bitwise OR&#39;ed with the <code>GV_ADD</code> argument to enable certain extra features. Those bits are:</p>

<dl>

<dt id="GV_ADDMULTI"><a class="permalink" href="perlguts.html#GV_ADDMULTI">#</a>GV_ADDMULTI</dt>
<dd>

<p>Marks the variable as multiply defined, thus preventing the:</p>

<pre><code class="plaintext">Name &lt;varname&gt; used only once: possible typo</code></pre>

<p>warning.</p>

</dd>
<dt id="GV_ADDWARN"><a class="permalink" href="perlguts.html#GV_ADDWARN">#</a>GV_ADDWARN</dt>
<dd>

<p>Issues the warning:</p>

<pre><code class="plaintext">Had to create &lt;varname&gt; unexpectedly</code></pre>

<p>if the variable did not exist before the function was called.</p>

</dd>
</dl>

<p>If you do not specify a package name, the variable is created in the current package.</p>

<h2 id="Reference-Counts-and-Mortality"><a class="permalink" href="perlguts.html#Reference-Counts-and-Mortality">#</a><a id="Reference"></a>Reference Counts and Mortality</h2>

<p>Perl uses a reference count-driven garbage collection mechanism. SVs, AVs, or HVs (xV for short in the following) start their life with a reference count of 1. If the reference count of an xV ever drops to 0, then it will be destroyed and its memory made available for reuse. At the most basic internal level, reference counts can be manipulated with the following macros:</p>

<pre><code>int SvREFCNT(SV* sv);
SV* SvREFCNT_inc(SV* sv);
void SvREFCNT_dec(SV* sv);</code></pre>

<p>(There are also suffixed versions of the increment and decrement macros, for situations where the full generality of these basic macros can be exchanged for some performance.)</p>

<p>However, the way a programmer should think about references is not so much in terms of the bare reference count, but in terms of <i>ownership</i> of references. A reference to an xV can be owned by any of a variety of entities: another xV, the Perl interpreter, an XS data structure, a piece of running code, or a dynamic scope. An xV generally does not know what entities own the references to it; it only knows how many references there are, which is the reference count.</p>

<p>To correctly maintain reference counts, it is essential to keep track of what references the XS code is manipulating. The programmer should always know where a reference has come from and who owns it, and be aware of any creation or destruction of references, and any transfers of ownership. Because ownership isn&#39;t represented explicitly in the xV data structures, only the reference count need be actually maintained by the code, and that means that this understanding of ownership is not actually evident in the code. For example, transferring ownership of a reference from one owner to another doesn&#39;t change the reference count at all, so may be achieved with no actual code. (The transferring code doesn&#39;t touch the referenced object, but does need to ensure that the former owner knows that it no longer owns the reference, and that the new owner knows that it now does.)</p>

<p>An xV that is visible at the Perl level should not become unreferenced and thus be destroyed. Normally, an object will only become unreferenced when it is no longer visible, often by the same means that makes it invisible. For example, a Perl reference value (RV) owns a reference to its referent, so if the RV is overwritten that reference gets destroyed, and the no-longer-reachable referent may be destroyed as a result.</p>

<p>Many functions have some kind of reference manipulation as part of their purpose. Sometimes this is documented in terms of ownership of references, and sometimes it is (less helpfully) documented in terms of changes to reference counts. For example, the <a href="perlapi.html#newRV_inc">newRV_inc()</a> function is documented to create a new RV (with reference count 1) and increment the reference count of the referent that was supplied by the caller. This is best understood as creating a new reference to the referent, which is owned by the created RV, and returning to the caller ownership of the sole reference to the RV. The <a href="perlapi.html#newRV_noinc">newRV_noinc()</a> function instead does not increment the reference count of the referent, but the RV nevertheless ends up owning a reference to the referent. It is therefore implied that the caller of <code>newRV_noinc()</code> is relinquishing a reference to the referent, making this conceptually a more complicated operation even though it does less to the data structures.</p>

<p>For example, imagine you want to return a reference from an XSUB function. Inside the XSUB routine, you create an SV which initially has just a single reference, owned by the XSUB routine. This reference needs to be disposed of before the routine is complete, otherwise it will leak, preventing the SV from ever being destroyed. So to create an RV referencing the SV, it is most convenient to pass the SV to <code>newRV_noinc()</code>, which consumes that reference. Now the XSUB routine no longer owns a reference to the SV, but does own a reference to the RV, which in turn owns a reference to the SV. The ownership of the reference to the RV is then transferred by the process of returning the RV from the XSUB.</p>

<p>There are some convenience functions available that can help with the destruction of xVs. These functions introduce the concept of &quot;mortality&quot;. Much documentation speaks of an xV itself being mortal, but this is misleading. It is really <i>a reference to</i> an xV that is mortal, and it is possible for there to be more than one mortal reference to a single xV. For a reference to be mortal means that it is owned by the temps stack, one of perl&#39;s many internal stacks, which will destroy that reference &quot;a short time later&quot;. Usually the &quot;short time later&quot; is the end of the current Perl statement. However, it gets more complicated around dynamic scopes: there can be multiple sets of mortal references hanging around at the same time, with different death dates. Internally, the actual determinant for when mortal xV references are destroyed depends on two macros, SAVETMPS and FREETMPS. See <a href="perlcall.html">perlcall</a> and <a href="perlxs.html">perlxs</a> and <a href="perlguts.html#Temporaries-Stack">&quot;Temporaries Stack&quot;</a> below for more details on these macros.</p>

<p>Mortal references are mainly used for xVs that are placed on perl&#39;s main stack. The stack is problematic for reference tracking, because it contains a lot of xV references, but doesn&#39;t own those references: they are not counted. Currently, there are many bugs resulting from xVs being destroyed while referenced by the stack, because the stack&#39;s uncounted references aren&#39;t enough to keep the xVs alive. So when putting an (uncounted) reference on the stack, it is vitally important to ensure that there will be a counted reference to the same xV that will last at least as long as the uncounted reference. But it&#39;s also important that that counted reference be cleaned up at an appropriate time, and not unduly prolong the xV&#39;s life. For there to be a mortal reference is often the best way to satisfy this requirement, especially if the xV was created especially to be put on the stack and would otherwise be unreferenced.</p>

<p>To create a mortal reference, use the functions:</p>

<pre><code class="plaintext">SV*  sv_newmortal()
SV*  sv_mortalcopy(SV*)
SV*  sv_2mortal(SV*)</code></pre>

<p><code>sv_newmortal()</code> creates an SV (with the undefined value) whose sole reference is mortal. <code>sv_mortalcopy()</code> creates an xV whose value is a copy of a supplied xV and whose sole reference is mortal. <code>sv_2mortal()</code> mortalises an existing xV reference: it transfers ownership of a reference from the caller to the temps stack. Because <code>sv_newmortal</code> gives the new SV no value, it must normally be given one via <code>sv_setpv</code>, <code>sv_setiv</code>, etc. :</p>

<pre><code>SV *tmp = sv_newmortal();
sv_setiv(tmp, an_integer);</code></pre>

<p>As that is multiple C statements it is quite common so see this idiom instead:</p>

<pre><code>SV *tmp = sv_2mortal(newSViv(an_integer));</code></pre>

<p>The mortal routines are not just for SVs; AVs and HVs can be made mortal by passing their address (type-casted to <code>SV*</code>) to the <code>sv_2mortal</code> or <code>sv_mortalcopy</code> routines.</p>

<h2 id="Stashes-and-Globs"><a class="permalink" href="perlguts.html#Stashes-and-Globs">#</a><a id="Stashes"></a>Stashes and Globs</h2>

<p>A <b>stash</b> is a hash that contains all variables that are defined within a package. Each key of the stash is a symbol name (shared by all the different types of objects that have the same name), and each value in the hash table is a GV (Glob Value). This GV in turn contains references to the various objects of that name, including (but not limited to) the following:</p>

<pre><code class="plaintext">Scalar Value
Array Value
Hash Value
I/O Handle
Format
Subroutine</code></pre>

<p>There is a single stash called <code>PL_defstash</code> that holds the items that exist in the <code>main</code> package. To get at the items in other packages, append the string &quot;::&quot; to the package name. The items in the <code>Foo</code> package are in the stash <code>Foo::</code> in PL_defstash. The items in the <code>Bar::Baz</code> package are in the stash <code>Baz::</code> in <code>Bar::</code>&#39;s stash.</p>

<p>To get the stash pointer for a particular package, use the function:</p>

<pre><code class="plaintext">HV*  gv_stashpv(const char* name, I32 flags)
HV*  gv_stashsv(SV*, I32 flags)</code></pre>

<p>The first function takes a literal string, the second uses the string stored in the SV. Remember that a stash is just a hash table, so you get back an <code>HV*</code>. The <code>flags</code> flag will create a new package if it is set to GV_ADD.</p>

<p>The name that <code>gv_stash*v</code> wants is the name of the package whose symbol table you want. The default package is called <code>main</code>. If you have multiply nested packages, pass their names to <code>gv_stash*v</code>, separated by <code>::</code> as in the Perl language itself.</p>

<p>Alternately, if you have an SV that is a blessed reference, you can find out the stash pointer by using:</p>

<pre><code>HV*  SvSTASH(SvRV(SV*));</code></pre>

<p>then use the following to get the package name itself:</p>

<pre><code>char*  HvNAME(HV* stash);</code></pre>

<p>If you need to bless or re-bless an object you can use the following function:</p>

<pre><code class="plaintext">SV*  sv_bless(SV*, HV* stash)</code></pre>

<p>where the first argument, an <code>SV*</code>, must be a reference, and the second argument is a stash. The returned <code>SV*</code> can now be used in the same way as any other SV.</p>

<p>For more information on references and blessings, consult <a href="perlref.html">perlref</a>.</p>

<h2 id="I/O-Handles"><a class="permalink" href="perlguts.html#I/O-Handles">#</a><a id="I"></a><a id="I-O-Handles"></a>I/O Handles</h2>

<p>Like AVs and HVs, IO objects are another type of non-scalar SV which may contain input and output <a href="perlapio.html">PerlIO</a> objects or a <code>DIR *</code> from opendir().</p>

<p>You can create a new IO object:</p>

<pre><code>IO*  newIO();</code></pre>

<p>Unlike other SVs, a new IO object is automatically blessed into the <a href="./IO::File.html">IO::File</a> class.</p>

<p>The IO object contains an input and output PerlIO handle:</p>

<pre><code>PerlIO *IoIFP(IO *io);
PerlIO *IoOFP(IO *io);</code></pre>

<p>Typically if the IO object has been opened on a file, the input handle is always present, but the output handle is only present if the file is open for output. For a file, if both are present they will be the same PerlIO object.</p>

<p>Distinct input and output PerlIO objects are created for sockets and character devices.</p>

<p>The IO object also contains other data associated with Perl I/O handles:</p>

<pre><code>IV IoLINES(io);                /* $. */
IV IoPAGE(io);                 /* $% */
IV IoPAGE_LEN(io);             /* $= */
IV IoLINES_LEFT(io);           /* $- */
char *IoTOP_NAME(io);          /* $^ */
GV *IoTOP_GV(io);              /* $^ */
char *IoFMT_NAME(io);          /* $~ */
GV *IoFMT_GV(io);              /* $~ */
char *IoBOTTOM_NAME(io);
GV *IoBOTTOM_GV(io);
char IoTYPE(io);
U8 IoFLAGS(io);</code></pre>

<p>Most of these are involved with <a href="perlform.html">formats</a>.</p>

<p>IoFLAGs() may contain a combination of flags, the most interesting of which are <code>IOf_FLUSH</code> (<code>$|</code>) for autoflush and <code>IOf_UNTAINT</code>, settable with <a href="./IO::Handle.html#%24io-%3Euntaint">IO::Handle&#39;s untaint() method</a>.</p>

<p>The IO object may also contains a directory handle:</p>

<pre><code>DIR *IoDIRP(io);</code></pre>

<p>suitable for use with PerlDir_read() etc.</p>

<p>All of these accessors macros are lvalues, there are no distinct <code>_set()</code> macros to modify the members of the IO object.</p>

<h2 id="Double-Typed-SVs"><a class="permalink" href="perlguts.html#Double-Typed-SVs">#</a><a id="Double"></a>Double-Typed SVs</h2>

<p>Scalar variables normally contain only one type of value, an integer, double, pointer, or reference. Perl will automatically convert the actual scalar data from the stored type into the requested type.</p>

<p>Some scalar variables contain more than one type of scalar data. For example, the variable <code>$!</code> contains either the numeric value of <code>errno</code> or its string equivalent from either <code>strerror</code> or <code>sys_errlist[]</code>.</p>

<p>To force multiple data values into an SV, you must do two things: use the <code>sv_set*v</code> routines to add the additional scalar type, then set a flag so that Perl will believe it contains more than one type of data. The four macros to set the flags are:</p>

<pre><code class="plaintext">SvIOK_on
SvNOK_on
SvPOK_on
SvROK_on</code></pre>

<p>The particular macro you must use depends on which <code>sv_set*v</code> routine you called first. This is because every <code>sv_set*v</code> routine turns on only the bit for the particular type of data being set, and turns off all the rest.</p>

<p>For example, to create a new Perl variable called &quot;dberror&quot; that contains both the numeric and descriptive string error values, you could use the following code:</p>

<pre><code>extern int  dberror;
extern char *dberror_list;

SV* sv = get_sv(&quot;dberror&quot;, GV_ADD);
sv_setiv(sv, (IV) dberror);
sv_setpv(sv, dberror_list[dberror]);
SvIOK_on(sv);</code></pre>

<p>If the order of <code>sv_setiv</code> and <code>sv_setpv</code> had been reversed, then the macro <code>SvPOK_on</code> would need to be called instead of <code>SvIOK_on</code>.</p>

<h2 id="Read-Only-Values"><a class="permalink" href="perlguts.html#Read-Only-Values">#</a><a id="Read"></a>Read-Only Values</h2>

<p>In Perl 5.16 and earlier, copy-on-write (see the next section) shared a flag bit with read-only scalars. So the only way to test whether <code>sv_setsv</code>, etc., will raise a &quot;Modification of a read-only value&quot; error in those versions is:</p>

<pre><code class="plaintext">SvREADONLY(sv) &amp;&amp; !SvIsCOW(sv)</code></pre>

<p>Under Perl 5.18 and later, SvREADONLY only applies to read-only variables, and, under 5.20, copy-on-write scalars can also be read-only, so the above check is incorrect. You just want:</p>

<pre><code class="plaintext">SvREADONLY(sv)</code></pre>

<p>If you need to do this check often, define your own macro like this:</p>

<pre><code class="plaintext">#if PERL_VERSION &gt;= 18
# define SvTRULYREADONLY(sv) SvREADONLY(sv)
#else
# define SvTRULYREADONLY(sv) (SvREADONLY(sv) &amp;&amp; !SvIsCOW(sv))
#endif</code></pre>

<h2 id="Copy-on-Write"><a class="permalink" href="perlguts.html#Copy-on-Write">#</a><a id="Copy"></a>Copy on Write</h2>

<p>Perl implements a copy-on-write (COW) mechanism for scalars, in which string copies are not immediately made when requested, but are deferred until made necessary by one or the other scalar changing. This is mostly transparent, but one must take care not to modify string buffers that are shared by multiple SVs.</p>

<p>You can test whether an SV is using copy-on-write with <code>SvIsCOW(sv)</code>.</p>

<p>You can force an SV to make its own copy of its string buffer by calling <code>sv_force_normal(sv)</code> or SvPV_force_nolen(sv).</p>

<p>If you want to make the SV drop its string buffer, use <code>sv_force_normal_flags(sv, SV_COW_DROP_PV)</code> or simply <code>sv_setsv(sv, NULL)</code>.</p>

<p>All of these functions will croak on read-only scalars (see the previous section for more on those).</p>

<p>To test that your code is behaving correctly and not modifying COW buffers, on systems that support <a href="http://man.he.net/man2/mmap">mmap(2)</a> (i.e., Unix) you can configure perl with <code>-Accflags=-DPERL_DEBUG_READONLY_COW</code> and it will turn buffer violations into crashes. You will find it to be marvellously slow, so you may want to skip perl&#39;s own tests.</p>

<h2 id="Magic-Variables"><a class="permalink" href="perlguts.html#Magic-Variables">#</a><a id="Magic"></a>Magic Variables</h2>

<p>[This section still under construction. Ignore everything here. Post no bills. Everything not permitted is forbidden.]</p>

<p>Any SV may be magical, that is, it has special features that a normal SV does not have. These features are stored in the SV structure in a linked list of <code>struct magic</code>&#39;s, typedef&#39;ed to <code>MAGIC</code>.</p>

<pre><code>struct magic {
    MAGIC*      mg_moremagic;
    MGVTBL*     mg_virtual;
    U16         mg_private;
    char        mg_type;
    U8          mg_flags;
    I32         mg_len;
    SV*         mg_obj;
    char*       mg_ptr;
};</code></pre>

<p>Note this is current as of patchlevel 0, and could change at any time.</p>

<h2 id="Assigning-Magic"><a class="permalink" href="perlguts.html#Assigning-Magic">#</a><a id="Assigning"></a>Assigning Magic</h2>

<p>Perl adds magic to an SV using the sv_magic function:</p>

<pre><code>void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);</code></pre>

<p>The <code>sv</code> argument is a pointer to the SV that is to acquire a new magical feature.</p>

<p>If <code>sv</code> is not already magical, Perl uses the <code>SvUPGRADE</code> macro to convert <code>sv</code> to type <code>SVt_PVMG</code>. Perl then continues by adding new magic to the beginning of the linked list of magical features. Any prior entry of the same type of magic is deleted. Note that this can be overridden, and multiple instances of the same type of magic can be associated with an SV.</p>

<p>The <code>name</code> and <code>namlen</code> arguments are used to associate a string with the magic, typically the name of a variable. <code>namlen</code> is stored in the <code>mg_len</code> field and if <code>name</code> is non-null then either a <code>savepvn</code> copy of <code>name</code> or <code>name</code> itself is stored in the <code>mg_ptr</code> field, depending on whether <code>namlen</code> is greater than zero or equal to zero respectively. As a special case, if <code>(name &amp;&amp; namlen == HEf_SVKEY)</code> then <code>name</code> is assumed to contain an <code>SV*</code> and is stored as-is with its REFCNT incremented.</p>

<p>The sv_magic function uses <code>how</code> to determine which, if any, predefined &quot;Magic Virtual Table&quot; should be assigned to the <code>mg_virtual</code> field. See the <a href="perlguts.html#Magic-Virtual-Tables">&quot;Magic Virtual Tables&quot;</a> section below. The <code>how</code> argument is also stored in the <code>mg_type</code> field. The value of <code>how</code> should be chosen from the set of macros <code>PERL_MAGIC_foo</code> found in <i>perl.h</i>. Note that before these macros were added, Perl internals used to directly use character literals, so you may occasionally come across old code or documentation referring to &#39;U&#39; magic rather than <code>PERL_MAGIC_uvar</code> for example.</p>

<p>The <code>obj</code> argument is stored in the <code>mg_obj</code> field of the <code>MAGIC</code> structure. If it is not the same as the <code>sv</code> argument, the reference count of the <code>obj</code> object is incremented. If it is the same, or if the <code>how</code> argument is <code>PERL_MAGIC_arylen</code>, <code>PERL_MAGIC_regdatum</code>, <code>PERL_MAGIC_regdata</code>, or if it is a NULL pointer, then <code>obj</code> is merely stored, without the reference count being incremented.</p>

<p>See also <code>sv_magicext</code> in <a href="perlapi.html">perlapi</a> for a more flexible way to add magic to an SV.</p>

<p>There is also a function to add magic to an <code>HV</code>:</p>

<pre><code>void hv_magic(HV *hv, GV *gv, int how);</code></pre>

<p>This simply calls <code>sv_magic</code> and coerces the <code>gv</code> argument into an <code>SV</code>.</p>

<p>To remove the magic from an SV, call the function sv_unmagic:</p>

<pre><code>int sv_unmagic(SV *sv, int type);</code></pre>

<p>The <code>type</code> argument should be equal to the <code>how</code> value when the <code>SV</code> was initially made magical.</p>

<p>However, note that <code>sv_unmagic</code> removes all magic of a certain <code>type</code> from the <code>SV</code>. If you want to remove only certain magic of a <code>type</code> based on the magic virtual table, use <code>sv_unmagicext</code> instead:</p>

<pre><code>int sv_unmagicext(SV *sv, int type, MGVTBL *vtbl);</code></pre>

<h2 id="Magic-Virtual-Tables"><a class="permalink" href="perlguts.html#Magic-Virtual-Tables">#</a><a id="Magic1"></a>Magic Virtual Tables</h2>

<p>The <code>mg_virtual</code> field in the <code>MAGIC</code> structure is a pointer to an <code>MGVTBL</code>, which is a structure of function pointers and stands for &quot;Magic Virtual Table&quot; to handle the various operations that might be applied to that variable.</p>

<p>The <code>MGVTBL</code> has five (or sometimes eight) pointers to the following routine types:</p>

<pre><code>int  (*svt_get)  (pTHX_ SV* sv, MAGIC* mg);
int  (*svt_set)  (pTHX_ SV* sv, MAGIC* mg);
U32  (*svt_len)  (pTHX_ SV* sv, MAGIC* mg);
int  (*svt_clear)(pTHX_ SV* sv, MAGIC* mg);
int  (*svt_free) (pTHX_ SV* sv, MAGIC* mg);

int  (*svt_copy) (pTHX_ SV *sv, MAGIC* mg, SV *nsv,
                                      const char *name, I32 namlen);
int  (*svt_dup)  (pTHX_ MAGIC *mg, CLONE_PARAMS *param);
int  (*svt_local)(pTHX_ SV *nsv, MAGIC *mg);</code></pre>

<p>This MGVTBL structure is set at compile-time in <i>perl.h</i> and there are currently 32 types. These different structures contain pointers to various routines that perform additional actions depending on which function is being called.</p>

<pre><code class="plaintext">Function pointer    Action taken
----------------    ------------
svt_get             Do something before the value of the SV is
                    retrieved.
svt_set             Do something after the SV is assigned a value.
svt_len             Report on the SV&#39;s length.
svt_clear           Clear something the SV represents.
svt_free            Free any extra storage associated with the SV.

svt_copy            copy tied variable magic to a tied element
svt_dup             duplicate a magic structure during thread cloning
svt_local           copy magic to local value during &#39;local&#39;</code></pre>

<p>For instance, the MGVTBL structure called <code>vtbl_sv</code> (which corresponds to an <code>mg_type</code> of <code>PERL_MAGIC_sv</code>) contains:</p>

<pre><code class="plaintext">{ magic_get, magic_set, magic_len, 0, 0 }</code></pre>

<p>Thus, when an SV is determined to be magical and of type <code>PERL_MAGIC_sv</code>, if a get operation is being performed, the routine <code>magic_get</code> is called. All the various routines for the various magical types begin with <code>magic_</code>. NOTE: the magic routines are not considered part of the Perl API, and may not be exported by the Perl library.</p>

<p>The last three slots are a recent addition, and for source code compatibility they are only checked for if one of the three flags MGf_COPY, MGf_DUP or MGf_LOCAL is set in mg_flags. This means that most code can continue declaring a vtable as a 5-element value. These three are currently used exclusively by the threading code, and are highly subject to change.</p>

<p>The current kinds of Magic Virtual Tables are:</p>

<pre><code>mg_type
(old-style char and macro)   MGVTBL         Type of magic
--------------------------   ------         -------------
\0 PERL_MAGIC_sv             vtbl_sv        Special scalar variable
#  PERL_MAGIC_arylen         vtbl_arylen    Array length ($#ary)
%  PERL_MAGIC_rhash          (none)         Extra data for restricted
                                            hashes
*  PERL_MAGIC_debugvar       vtbl_debugvar  $DB::single, signal, trace
                                            vars
.  PERL_MAGIC_pos            vtbl_pos       pos() lvalue
:  PERL_MAGIC_symtab         (none)         Extra data for symbol
                                            tables
&lt;  PERL_MAGIC_backref        vtbl_backref   For weak ref data
@  PERL_MAGIC_arylen_p       (none)         To move arylen out of XPVAV
B  PERL_MAGIC_bm             vtbl_regexp    Boyer-Moore 
                                            (fast string search)
c  PERL_MAGIC_overload_table vtbl_ovrld     Holds overload table 
                                            (AMT) on stash
D  PERL_MAGIC_regdata        vtbl_regdata   Regex match position data 
                                            (@+ and @- vars)
d  PERL_MAGIC_regdatum       vtbl_regdatum  Regex match position data
                                            element
E  PERL_MAGIC_env            vtbl_env       %ENV hash
e  PERL_MAGIC_envelem        vtbl_envelem   %ENV hash element
f  PERL_MAGIC_fm             vtbl_regexp    Formline 
                                            (&#39;compiled&#39; format)
g  PERL_MAGIC_regex_global   vtbl_mglob     m//g target
H  PERL_MAGIC_hints          vtbl_hints     %^H hash
h  PERL_MAGIC_hintselem      vtbl_hintselem %^H hash element
I  PERL_MAGIC_isa            vtbl_isa       @ISA array
i  PERL_MAGIC_isaelem        vtbl_isaelem   @ISA array element
k  PERL_MAGIC_nkeys          vtbl_nkeys     scalar(keys()) lvalue
L  PERL_MAGIC_dbfile         (none)         Debugger %_&lt;filename
l  PERL_MAGIC_dbline         vtbl_dbline    Debugger %_&lt;filename
                                            element
N  PERL_MAGIC_shared         (none)         Shared between threads
n  PERL_MAGIC_shared_scalar  (none)         Shared between threads
o  PERL_MAGIC_collxfrm       vtbl_collxfrm  Locale transformation
P  PERL_MAGIC_tied           vtbl_pack      Tied array or hash
p  PERL_MAGIC_tiedelem       vtbl_packelem  Tied array or hash element
q  PERL_MAGIC_tiedscalar     vtbl_packelem  Tied scalar or handle
r  PERL_MAGIC_qr             vtbl_regexp    Precompiled qr// regex
S  PERL_MAGIC_sig            (none)         %SIG hash
s  PERL_MAGIC_sigelem        vtbl_sigelem   %SIG hash element
t  PERL_MAGIC_taint          vtbl_taint     Taintedness
U  PERL_MAGIC_uvar           vtbl_uvar      Available for use by
                                            extensions
u  PERL_MAGIC_uvar_elem      (none)         Reserved for use by
                                            extensions
V  PERL_MAGIC_vstring        (none)         SV was vstring literal
v  PERL_MAGIC_vec            vtbl_vec       vec() lvalue
w  PERL_MAGIC_utf8           vtbl_utf8      Cached UTF-8 information
x  PERL_MAGIC_substr         vtbl_substr    substr() lvalue
Y  PERL_MAGIC_nonelem        vtbl_nonelem   Array element that does not
                                            exist
y  PERL_MAGIC_defelem        vtbl_defelem   Shadow &quot;foreach&quot; iterator
                                            variable / smart parameter
                                            vivification
\  PERL_MAGIC_lvref          vtbl_lvref     Lvalue reference
                                            constructor
]  PERL_MAGIC_checkcall      vtbl_checkcall Inlining/mutation of call
                                            to this CV
~  PERL_MAGIC_ext            (none)         Available for use by
                                            extensions</code></pre>

<p>When an uppercase and lowercase letter both exist in the table, then the uppercase letter is typically used to represent some kind of composite type (a list or a hash), and the lowercase letter is used to represent an element of that composite type. Some internals code makes use of this case relationship. However, &#39;v&#39; and &#39;V&#39; (vec and v-string) are in no way related.</p>

<p>The <code>PERL_MAGIC_ext</code> and <code>PERL_MAGIC_uvar</code> magic types are defined specifically for use by extensions and will not be used by perl itself. Extensions can use <code>PERL_MAGIC_ext</code> magic to &#39;attach&#39; private information to variables (typically objects). This is especially useful because there is no way for normal perl code to corrupt this private information (unlike using extra elements of a hash object).</p>

<p>Similarly, <code>PERL_MAGIC_uvar</code> magic can be used much like tie() to call a C function any time a scalar&#39;s value is used or changed. The <code>MAGIC</code>&#39;s <code>mg_ptr</code> field points to a <code>ufuncs</code> structure:</p>

<pre><code>struct ufuncs {
    I32 (*uf_val)(pTHX_ IV, SV*);
    I32 (*uf_set)(pTHX_ IV, SV*);
    IV uf_index;
};</code></pre>

<p>When the SV is read from or written to, the <code>uf_val</code> or <code>uf_set</code> function will be called with <code>uf_index</code> as the first arg and a pointer to the SV as the second. A simple example of how to add <code>PERL_MAGIC_uvar</code> magic is shown below. Note that the ufuncs structure is copied by sv_magic, so you can safely allocate it on the stack.</p>

<pre><code>void
Umagic(sv)
    SV *sv;
PREINIT:
    struct ufuncs uf;
CODE:
    uf.uf_val   = &amp;my_get_fn;
    uf.uf_set   = &amp;my_set_fn;
    uf.uf_index = 0;
    sv_magic(sv, 0, PERL_MAGIC_uvar, (char*)&amp;uf, sizeof(uf));</code></pre>

<p>Attaching <code>PERL_MAGIC_uvar</code> to arrays is permissible but has no effect.</p>

<p>For hashes there is a specialized hook that gives control over hash keys (but not values). This hook calls <code>PERL_MAGIC_uvar</code> &#39;get&#39; magic if the &quot;set&quot; function in the <code>ufuncs</code> structure is NULL. The hook is activated whenever the hash is accessed with a key specified as an <code>SV</code> through the functions <code>hv_store_ent</code>, <code>hv_fetch_ent</code>, <code>hv_delete_ent</code>, and <code>hv_exists_ent</code>. Accessing the key as a string through the functions without the <code>..._ent</code> suffix circumvents the hook. See <a href="./Hash::Util::FieldHash.html#GUTS">&quot;GUTS&quot; in Hash::Util::FieldHash</a> for a detailed description.</p>

<p>Note that because multiple extensions may be using <code>PERL_MAGIC_ext</code> or <code>PERL_MAGIC_uvar</code> magic, it is important for extensions to take extra care to avoid conflict. Typically only using the magic on objects blessed into the same class as the extension is sufficient. For <code>PERL_MAGIC_ext</code> magic, it is usually a good idea to define an <code>MGVTBL</code>, even if all its fields will be <code>0</code>, so that individual <code>MAGIC</code> pointers can be identified as a particular kind of magic using their magic virtual table. <code>mg_findext</code> provides an easy way to do that:</p>

<pre><code>STATIC MGVTBL my_vtbl = { 0, 0, 0, 0, 0, 0, 0, 0 };

MAGIC *mg;
if ((mg = mg_findext(sv, PERL_MAGIC_ext, &amp;my_vtbl))) {
    /* this is really ours, not another module&#39;s PERL_MAGIC_ext */
    my_priv_data_t *priv = (my_priv_data_t *)mg-&gt;mg_ptr;
    ...
}</code></pre>

<p>Also note that the <code>sv_set*()</code> and <code>sv_cat*()</code> functions described earlier do <b>not</b> invoke &#39;set&#39; magic on their targets. This must be done by the user either by calling the <code>SvSETMAGIC()</code> macro after calling these functions, or by using one of the <code>sv_set*_mg()</code> or <code>sv_cat*_mg()</code> functions. Similarly, generic C code must call the <code>SvGETMAGIC()</code> macro to invoke any &#39;get&#39; magic if they use an SV obtained from external sources in functions that don&#39;t handle magic. See <a href="perlapi.html">perlapi</a> for a description of these functions. For example, calls to the <code>sv_cat*()</code> functions typically need to be followed by <code>SvSETMAGIC()</code>, but they don&#39;t need a prior <code>SvGETMAGIC()</code> since their implementation handles &#39;get&#39; magic.</p>

<h2 id="Finding-Magic"><a class="permalink" href="perlguts.html#Finding-Magic">#</a><a id="Finding"></a>Finding Magic</h2>

<pre><code class="plaintext">MAGIC *mg_find(SV *sv, int type); /* Finds the magic pointer of that
                                   * type */</code></pre>

<p>This routine returns a pointer to a <code>MAGIC</code> structure stored in the SV. If the SV does not have that magical feature, <code>NULL</code> is returned. If the SV has multiple instances of that magical feature, the first one will be returned. <code>mg_findext</code> can be used to find a <code>MAGIC</code> structure of an SV based on both its magic type and its magic virtual table:</p>

<pre><code>MAGIC *mg_findext(SV *sv, int type, MGVTBL *vtbl);</code></pre>

<p>Also, if the SV passed to <code>mg_find</code> or <code>mg_findext</code> is not of type SVt_PVMG, Perl may core dump.</p>

<pre><code>int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);</code></pre>

<p>This routine checks to see what types of magic <code>sv</code> has. If the mg_type field is an uppercase letter, then the mg_obj is copied to <code>nsv</code>, but the mg_type field is changed to be the lowercase letter.</p>

<h2 id="Understanding-the-Magic-of-Tied-Hashes-and-Arrays"><a class="permalink" href="perlguts.html#Understanding-the-Magic-of-Tied-Hashes-and-Arrays">#</a><a id="Understanding"></a>Understanding the Magic of Tied Hashes and Arrays</h2>

<p>Tied hashes and arrays are magical beasts of the <code>PERL_MAGIC_tied</code> magic type.</p>

<p>WARNING: As of the 5.004 release, proper usage of the array and hash access functions requires understanding a few caveats. Some of these caveats are actually considered bugs in the API, to be fixed in later releases, and are bracketed with [MAYCHANGE] below. If you find yourself actually applying such information in this section, be aware that the behavior may change in the future, umm, without warning.</p>

<p>The perl tie function associates a variable with an object that implements the various GET, SET, etc methods. To perform the equivalent of the perl tie function from an XSUB, you must mimic this behaviour. The code below carries out the necessary steps -- firstly it creates a new hash, and then creates a second hash which it blesses into the class which will implement the tie methods. Lastly it ties the two hashes together, and returns a reference to the new tied hash. Note that the code below does NOT call the TIEHASH method in the MyTie class - see <a href="perlguts.html#Calling-Perl-Routines-from-within-C-Programs">&quot;Calling Perl Routines from within C Programs&quot;</a> for details on how to do this.</p>

<pre><code>SV*
mytie()
PREINIT:
    HV *hash;
    HV *stash;
    SV *tie;
CODE:
    hash = newHV();
    tie = newRV_noinc((SV*)newHV());
    stash = gv_stashpv(&quot;MyTie&quot;, GV_ADD);
    sv_bless(tie, stash);
    hv_magic(hash, (GV*)tie, PERL_MAGIC_tied);
    RETVAL = newRV_noinc(hash);
OUTPUT:
    RETVAL</code></pre>

<p>The <code>av_store</code> function, when given a tied array argument, merely copies the magic of the array onto the value to be &quot;stored&quot;, using <code>mg_copy</code>. It may also return NULL, indicating that the value did not actually need to be stored in the array. [MAYCHANGE] After a call to <code>av_store</code> on a tied array, the caller will usually need to call <code>mg_set(val)</code> to actually invoke the perl level &quot;STORE&quot; method on the TIEARRAY object. If <code>av_store</code> did return NULL, a call to <code>SvREFCNT_dec(val)</code> will also be usually necessary to avoid a memory leak. [/MAYCHANGE]</p>

<p>The previous paragraph is applicable verbatim to tied hash access using the <code>hv_store</code> and <code>hv_store_ent</code> functions as well.</p>

<p><code>av_fetch</code> and the corresponding hash functions <code>hv_fetch</code> and <code>hv_fetch_ent</code> actually return an undefined mortal value whose magic has been initialized using <code>mg_copy</code>. Note the value so returned does not need to be deallocated, as it is already mortal. [MAYCHANGE] But you will need to call <code>mg_get()</code> on the returned value in order to actually invoke the perl level &quot;FETCH&quot; method on the underlying TIE object. Similarly, you may also call <code>mg_set()</code> on the return value after possibly assigning a suitable value to it using <code>sv_setsv</code>, which will invoke the &quot;STORE&quot; method on the TIE object. [/MAYCHANGE]</p>

<p>[MAYCHANGE] In other words, the array or hash fetch/store functions don&#39;t really fetch and store actual values in the case of tied arrays and hashes. They merely call <code>mg_copy</code> to attach magic to the values that were meant to be &quot;stored&quot; or &quot;fetched&quot;. Later calls to <code>mg_get</code> and <code>mg_set</code> actually do the job of invoking the TIE methods on the underlying objects. Thus the magic mechanism currently implements a kind of lazy access to arrays and hashes.</p>

<p>Currently (as of perl version 5.004), use of the hash and array access functions requires the user to be aware of whether they are operating on &quot;normal&quot; hashes and arrays, or on their tied variants. The API may be changed to provide more transparent access to both tied and normal data types in future versions. [/MAYCHANGE]</p>

<p>You would do well to understand that the TIEARRAY and TIEHASH interfaces are mere sugar to invoke some perl method calls while using the uniform hash and array syntax. The use of this sugar imposes some overhead (typically about two to four extra opcodes per FETCH/STORE operation, in addition to the creation of all the mortal variables required to invoke the methods). This overhead will be comparatively small if the TIE methods are themselves substantial, but if they are only a few statements long, the overhead will not be insignificant.</p>

<h2 id="Localizing-changes"><a class="permalink" href="perlguts.html#Localizing-changes">#</a><a id="Localizing"></a>Localizing changes</h2>

<p>Perl has a very handy construction</p>

<pre><code>{
  local $var = 2;
  ...
}</code></pre>

<p>This construction is <i>approximately</i> equivalent to</p>

<pre><code>{
  my $oldvar = $var;
  $var = 2;
  ...
  $var = $oldvar;
}</code></pre>

<p>The biggest difference is that the first construction would reinstate the initial value of $var, irrespective of how control exits the block: <code>goto</code>, <code>return</code>, <code>die</code>/<code>eval</code>, etc. It is a little bit more efficient as well.</p>

<p>There is a way to achieve a similar task from C via Perl API: create a <i>pseudo-block</i>, and arrange for some changes to be automatically undone at the end of it, either explicit, or via a non-local exit (via die()). A <i>block</i>-like construct is created by a pair of <code>ENTER</code>/<code>LEAVE</code> macros (see <a href="perlcall.html#Returning-a-Scalar">&quot;Returning a Scalar&quot; in perlcall</a>). Such a construct may be created specially for some important localized task, or an existing one (like boundaries of enclosing Perl subroutine/block, or an existing pair for freeing TMPs) may be used. (In the second case the overhead of additional localization must be almost negligible.) Note that any XSUB is automatically enclosed in an <code>ENTER</code>/<code>LEAVE</code> pair.</p>

<p>Inside such a <i>pseudo-block</i> the following service is available:</p>

<dl>

<dt id="SAVEINT(int-i)"><a class="permalink" href="perlguts.html#SAVEINT(int-i)">#</a><a id="SAVEINT"></a><a id="SAVEINT-int-i"></a><code>SAVEINT(int i)</code></dt>
<dd>

</dd>
<dt id="SAVEIV(IV-i)"><a class="permalink" href="perlguts.html#SAVEIV(IV-i)">#</a><a id="SAVEIV"></a><a id="SAVEIV-IV-i"></a><code>SAVEIV(IV i)</code></dt>
<dd>

</dd>
<dt id="SAVEI32(I32-i)"><a class="permalink" href="perlguts.html#SAVEI32(I32-i)">#</a><a id="SAVEI32"></a><a id="SAVEI32-I32-i"></a><code>SAVEI32(I32 i)</code></dt>
<dd>

</dd>
<dt id="SAVELONG(long-i)"><a class="permalink" href="perlguts.html#SAVELONG(long-i)">#</a><a id="SAVELONG"></a><a id="SAVELONG-long-i"></a><code>SAVELONG(long i)</code></dt>
<dd>

</dd>
<dt id="SAVEI8(I8-i)"><a class="permalink" href="perlguts.html#SAVEI8(I8-i)">#</a><a id="SAVEI8"></a><a id="SAVEI8-I8-i"></a><code>SAVEI8(I8 i)</code></dt>
<dd>

</dd>
<dt id="SAVEI16(I16-i)"><a class="permalink" href="perlguts.html#SAVEI16(I16-i)">#</a><a id="SAVEI16"></a><a id="SAVEI16-I16-i"></a><code>SAVEI16(I16 i)</code></dt>
<dd>

</dd>
<dt id="SAVEBOOL(int-i)"><a class="permalink" href="perlguts.html#SAVEBOOL(int-i)">#</a><a id="SAVEBOOL"></a><a id="SAVEBOOL-int-i"></a><code>SAVEBOOL(int i)</code></dt>
<dd>

<p>These macros arrange things to restore the value of integer variable <code>i</code> at the end of the enclosing <i>pseudo-block</i>.</p>

</dd>
<dt id="SAVESPTR(s)"><a class="permalink" href="perlguts.html#SAVESPTR(s)">#</a><a id="SAVESPTR"></a><a id="SAVESPTR-s"></a><code>SAVESPTR(s)</code></dt>
<dd>

</dd>
<dt id="SAVEPPTR(p)"><a class="permalink" href="perlguts.html#SAVEPPTR(p)">#</a><a id="SAVEPPTR"></a><a id="SAVEPPTR-p"></a><code>SAVEPPTR(p)</code></dt>
<dd>

<p>These macros arrange things to restore the value of pointers <code>s</code> and <code>p</code>. <code>s</code> must be a pointer of a type which survives conversion to <code>SV*</code> and back, <code>p</code> should be able to survive conversion to <code>char*</code> and back.</p>

</dd>
<dt id="SAVEFREESV(SV-*sv)"><a class="permalink" href="perlguts.html#SAVEFREESV(SV-*sv)">#</a><a id="SAVEFREESV"></a><a id="SAVEFREESV-SV-sv"></a><code>SAVEFREESV(SV *sv)</code></dt>
<dd>

<p>The refcount of <code>sv</code> will be decremented at the end of <i>pseudo-block</i>. This is similar to <code>sv_2mortal</code> in that it is also a mechanism for doing a delayed <code>SvREFCNT_dec</code>. However, while <code>sv_2mortal</code> extends the lifetime of <code>sv</code> until the beginning of the next statement, <code>SAVEFREESV</code> extends it until the end of the enclosing scope. These lifetimes can be wildly different.</p>

<p>Also compare <code>SAVEMORTALIZESV</code>.</p>

</dd>
<dt id="SAVEMORTALIZESV(SV-*sv)"><a class="permalink" href="perlguts.html#SAVEMORTALIZESV(SV-*sv)">#</a><a id="SAVEMORTALIZESV"></a><a id="SAVEMORTALIZESV-SV-sv"></a><code>SAVEMORTALIZESV(SV *sv)</code></dt>
<dd>

<p>Just like <code>SAVEFREESV</code>, but mortalizes <code>sv</code> at the end of the current scope instead of decrementing its reference count. This usually has the effect of keeping <code>sv</code> alive until the statement that called the currently live scope has finished executing.</p>

</dd>
<dt id="SAVEFREEOP(OP-*op)"><a class="permalink" href="perlguts.html#SAVEFREEOP(OP-*op)">#</a><a id="SAVEFREEOP"></a><a id="SAVEFREEOP-OP-op"></a><code>SAVEFREEOP(OP *op)</code></dt>
<dd>

<p>The <code>OP *</code> is op_free()ed at the end of <i>pseudo-block</i>.</p>

</dd>
<dt id="SAVEFREEPV(p)"><a class="permalink" href="perlguts.html#SAVEFREEPV(p)">#</a><a id="SAVEFREEPV"></a><a id="SAVEFREEPV-p"></a><code>SAVEFREEPV(p)</code></dt>
<dd>

<p>The chunk of memory which is pointed to by <code>p</code> is Safefree()ed at the end of <i>pseudo-block</i>.</p>

</dd>
<dt id="SAVECLEARSV(SV-*sv)"><a class="permalink" href="perlguts.html#SAVECLEARSV(SV-*sv)">#</a><a id="SAVECLEARSV"></a><a id="SAVECLEARSV-SV-sv"></a><code>SAVECLEARSV(SV *sv)</code></dt>
<dd>

<p>Clears a slot in the current scratchpad which corresponds to <code>sv</code> at the end of <i>pseudo-block</i>.</p>

</dd>
<dt id="SAVEDELETE(HV-*hv,-char-*key,-I32-length)"><a class="permalink" href="perlguts.html#SAVEDELETE(HV-*hv,-char-*key,-I32-length)">#</a><a id="SAVEDELETE"></a><a id="SAVEDELETE-HV-hv-char-key-I32-length"></a><code>SAVEDELETE(HV *hv, char *key, I32 length)</code></dt>
<dd>

<p>The key <code>key</code> of <code>hv</code> is deleted at the end of <i>pseudo-block</i>. The string pointed to by <code>key</code> is Safefree()ed. If one has a <i>key</i> in short-lived storage, the corresponding string may be reallocated like this:</p>

<pre><code>SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));</code></pre>

</dd>
<dt id="SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t-f,-void-*p)"><a class="permalink" href="perlguts.html#SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t-f,-void-*p)">#</a><a id="SAVEDESTRUCTOR"></a><a id="SAVEDESTRUCTOR-DESTRUCTORFUNC_NOCONTEXT_t-f-void-p"></a><code>SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)</code></dt>
<dd>

<p>At the end of <i>pseudo-block</i> the function <code>f</code> is called with the only argument <code>p</code>.</p>

</dd>
<dt id="SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t-f,-void-*p)"><a class="permalink" href="perlguts.html#SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t-f,-void-*p)">#</a><a id="SAVEDESTRUCTOR_X"></a><a id="SAVEDESTRUCTOR_X-DESTRUCTORFUNC_t-f-void-p"></a><code>SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)</code></dt>
<dd>

<p>At the end of <i>pseudo-block</i> the function <code>f</code> is called with the implicit context argument (if any), and <code>p</code>.</p>

</dd>
<dt id="SAVESTACK_POS()"><a class="permalink" href="perlguts.html#SAVESTACK_POS()">#</a><a id="SAVESTACK_POS"></a><code>SAVESTACK_POS()</code></dt>
<dd>

<p>The current offset on the Perl internal stack (cf. <code>SP</code>) is restored at the end of <i>pseudo-block</i>.</p>

</dd>
</dl>

<p>The following API list contains functions, thus one needs to provide pointers to the modifiable data explicitly (either C pointers, or Perlish <code>GV *</code>s). Where the above macros take <code>int</code>, a similar function takes <code>int *</code>.</p>

<p>Other macros above have functions implementing them, but its probably best to just use the macro, and not those or the ones below.</p>

<dl>

<dt id="SV*-save_scalar(GV-*gv)"><a class="permalink" href="perlguts.html#SV*-save_scalar(GV-*gv)">#</a><a id="SV"></a><a id="SV-save_scalar-GV-gv"></a><code>SV* save_scalar(GV *gv)</code></dt>
<dd>

<p>Equivalent to Perl code <code>local $gv</code>.</p>

</dd>
<dt id="AV*-save_ary(GV-*gv)"><a class="permalink" href="perlguts.html#AV*-save_ary(GV-*gv)">#</a><a id="AV"></a><a id="AV-save_ary-GV-gv"></a><code>AV* save_ary(GV *gv)</code></dt>
<dd>

</dd>
<dt id="HV*-save_hash(GV-*gv)"><a class="permalink" href="perlguts.html#HV*-save_hash(GV-*gv)">#</a><a id="HV"></a><a id="HV-save_hash-GV-gv"></a><code>HV* save_hash(GV *gv)</code></dt>
<dd>

<p>Similar to <code>save_scalar</code>, but localize <code>@gv</code> and <code>%gv</code>.</p>

</dd>
<dt id="void-save_item(SV-*item)"><a class="permalink" href="perlguts.html#void-save_item(SV-*item)">#</a><a id="void"></a><a id="void-save_item-SV-item"></a><code>void save_item(SV *item)</code></dt>
<dd>

<p>Duplicates the current value of <code>SV</code>. On the exit from the current <code>ENTER</code>/<code>LEAVE</code> <i>pseudo-block</i> the value of <code>SV</code> will be restored using the stored value. It doesn&#39;t handle magic. Use <code>save_scalar</code> if magic is affected.</p>

</dd>
<dt id="void-save_list(SV-**sarg,-I32-maxsarg)"><a class="permalink" href="perlguts.html#void-save_list(SV-**sarg,-I32-maxsarg)">#</a><a id="void1"></a><a id="void-save_list-SV-sarg-I32-maxsarg"></a><code>void save_list(SV **sarg, I32 maxsarg)</code></dt>
<dd>

<p>A variant of <code>save_item</code> which takes multiple arguments via an array <code>sarg</code> of <code>SV*</code> of length <code>maxsarg</code>.</p>

</dd>
<dt id="SV*-save_svref(SV-**sptr)"><a class="permalink" href="perlguts.html#SV*-save_svref(SV-**sptr)">#</a><a id="SV1"></a><a id="SV-save_svref-SV-sptr"></a><code>SV* save_svref(SV **sptr)</code></dt>
<dd>

<p>Similar to <code>save_scalar</code>, but will reinstate an <code>SV *</code>.</p>

</dd>
<dt id="void-save_aptr(AV-**aptr)"><a class="permalink" href="perlguts.html#void-save_aptr(AV-**aptr)">#</a><a id="void2"></a><a id="void-save_aptr-AV-aptr"></a><code>void save_aptr(AV **aptr)</code></dt>
<dd>

</dd>
<dt id="void-save_hptr(HV-**hptr)"><a class="permalink" href="perlguts.html#void-save_hptr(HV-**hptr)">#</a><a id="void3"></a><a id="void-save_hptr-HV-hptr"></a><code>void save_hptr(HV **hptr)</code></dt>
<dd>

<p>Similar to <code>save_svref</code>, but localize <code>AV *</code> and <code>HV *</code>.</p>

</dd>
</dl>

<p>The <code>Alias</code> module implements localization of the basic types within the <i>caller&#39;s scope</i>. People who are interested in how to localize things in the containing scope should take a look there too.</p>

<h1 id="Subroutines"><a class="permalink" href="perlguts.html#Subroutines">#</a>Subroutines</h1>

<h2 id="XSUBs-and-the-Argument-Stack"><a class="permalink" href="perlguts.html#XSUBs-and-the-Argument-Stack">#</a><a id="XSUBs"></a>XSUBs and the Argument Stack</h2>

<p>The XSUB mechanism is a simple way for Perl programs to access C subroutines. An XSUB routine will have a stack that contains the arguments from the Perl program, and a way to map from the Perl data structures to a C equivalent.</p>

<p>The stack arguments are accessible through the <code>ST(n)</code> macro, which returns the <code>n</code>&#39;th stack argument. Argument 0 is the first argument passed in the Perl subroutine call. These arguments are <code>SV*</code>, and can be used anywhere an <code>SV*</code> is used.</p>

<p>Most of the time, output from the C routine can be handled through use of the RETVAL and OUTPUT directives. However, there are some cases where the argument stack is not already long enough to handle all the return values. An example is the POSIX tzname() call, which takes no arguments, but returns two, the local time zone&#39;s standard and summer time abbreviations.</p>

<p>To handle this situation, the PPCODE directive is used and the stack is extended using the macro:</p>

<pre><code>EXTEND(SP, num);</code></pre>

<p>where <code>SP</code> is the macro that represents the local copy of the stack pointer, and <code>num</code> is the number of elements the stack should be extended by.</p>

<p>Now that there is room on the stack, values can be pushed on it using <code>PUSHs</code> macro. The pushed values will often need to be &quot;mortal&quot; (See <a href="perlguts.html#Reference-Counts-and-Mortality">&quot;Reference Counts and Mortality&quot;</a>):</p>

<pre><code class="plaintext">PUSHs(sv_2mortal(newSViv(an_integer)))
PUSHs(sv_2mortal(newSVuv(an_unsigned_integer)))
PUSHs(sv_2mortal(newSVnv(a_double)))
PUSHs(sv_2mortal(newSVpv(&quot;Some String&quot;,0)))
/* Although the last example is better written as the more
 * efficient: */
PUSHs(newSVpvs_flags(&quot;Some String&quot;, SVs_TEMP))</code></pre>

<p>And now the Perl program calling <code>tzname</code>, the two values will be assigned as in:</p>

<pre><code>($standard_abbrev, $summer_abbrev) = POSIX::tzname;</code></pre>

<p>An alternate (and possibly simpler) method to pushing values on the stack is to use the macro:</p>

<pre><code class="plaintext">XPUSHs(SV*)</code></pre>

<p>This macro automatically adjusts the stack for you, if needed. Thus, you do not need to call <code>EXTEND</code> to extend the stack.</p>

<p>Despite their suggestions in earlier versions of this document the macros <code>(X)PUSH[iunp]</code> are <i>not</i> suited to XSUBs which return multiple results. For that, either stick to the <code>(X)PUSHs</code> macros shown above, or use the new <code>m(X)PUSH[iunp]</code> macros instead; see <a href="perlguts.html#Putting-a-C-value-on-Perl-stack">&quot;Putting a C value on Perl stack&quot;</a>.</p>

<p>For more information, consult <a href="perlxs.html">perlxs</a> and <a href="perlxstut.html">perlxstut</a>.</p>

<h2 id="Autoloading-with-XSUBs"><a class="permalink" href="perlguts.html#Autoloading-with-XSUBs">#</a><a id="Autoloading"></a>Autoloading with XSUBs</h2>

<p>If an AUTOLOAD routine is an XSUB, as with Perl subroutines, Perl puts the fully-qualified name of the autoloaded subroutine in the $AUTOLOAD variable of the XSUB&#39;s package.</p>

<p>But it also puts the same information in certain fields of the XSUB itself:</p>

<pre><code>HV *stash           = CvSTASH(cv);
const char *subname = SvPVX(cv);
STRLEN name_length  = SvCUR(cv); /* in bytes */
U32 is_utf8         = SvUTF8(cv);</code></pre>

<p><code>SvPVX(cv)</code> contains just the sub name itself, not including the package. For an AUTOLOAD routine in UNIVERSAL or one of its superclasses, <code>CvSTASH(cv)</code> returns NULL during a method call on a nonexistent package.</p>

<p><b>Note</b>: Setting $AUTOLOAD stopped working in 5.6.1, which did not support XS AUTOLOAD subs at all. Perl 5.8.0 introduced the use of fields in the XSUB itself. Perl 5.16.0 restored the setting of $AUTOLOAD. If you need to support 5.8-5.14, use the XSUB&#39;s fields.</p>

<h2 id="Calling-Perl-Routines-from-within-C-Programs"><a class="permalink" href="perlguts.html#Calling-Perl-Routines-from-within-C-Programs">#</a><a id="Calling"></a>Calling Perl Routines from within C Programs</h2>

<p>There are four routines that can be used to call a Perl subroutine from within a C program. These four are:</p>

<pre><code>I32  call_sv(SV*, I32);
I32  call_pv(const char*, I32);
I32  call_method(const char*, I32);
I32  call_argv(const char*, I32, char**);</code></pre>

<p>The routine most often used is <code>call_sv</code>. The <code>SV*</code> argument contains either the name of the Perl subroutine to be called, or a reference to the subroutine. The second argument consists of flags that control the context in which the subroutine is called, whether or not the subroutine is being passed arguments, how errors should be trapped, and how to treat return values.</p>

<p>All four routines return the number of arguments that the subroutine returned on the Perl stack.</p>

<p>These routines used to be called <code>perl_call_sv</code>, etc., before Perl v5.6.0, but those names are now deprecated; macros of the same name are provided for compatibility.</p>

<p>When using any of these routines (except <code>call_argv</code>), the programmer must manipulate the Perl stack. These include the following macros and functions:</p>

<pre><code class="plaintext">dSP
SP
PUSHMARK()
PUTBACK
SPAGAIN
ENTER
SAVETMPS
FREETMPS
LEAVE
XPUSH*()
POP*()</code></pre>

<p>For a detailed description of calling conventions from C to Perl, consult <a href="perlcall.html">perlcall</a>.</p>

<h2 id="Putting-a-C-value-on-Perl-stack"><a class="permalink" href="perlguts.html#Putting-a-C-value-on-Perl-stack">#</a><a id="Putting"></a>Putting a C value on Perl stack</h2>

<p>A lot of opcodes (this is an elementary operation in the internal perl stack machine) put an SV* on the stack. However, as an optimization the corresponding SV is (usually) not recreated each time. The opcodes reuse specially assigned SVs (<i>target</i>s) which are (as a corollary) not constantly freed/created.</p>

<p>Each of the targets is created only once (but see <a href="perlguts.html#Scratchpads-and-recursion">&quot;Scratchpads and recursion&quot;</a> below), and when an opcode needs to put an integer, a double, or a string on stack, it just sets the corresponding parts of its <i>target</i> and puts the <i>target</i> on stack.</p>

<p>The macro to put this target on stack is <code>PUSHTARG</code>, and it is directly used in some opcodes, as well as indirectly in zillions of others, which use it via <code>(X)PUSH[iunp]</code>.</p>

<p>Because the target is reused, you must be careful when pushing multiple values on the stack. The following code will not do what you think:</p>

<pre><code>XPUSHi(10);
XPUSHi(20);</code></pre>

<p>This translates as &quot;set <code>TARG</code> to 10, push a pointer to <code>TARG</code> onto the stack; set <code>TARG</code> to 20, push a pointer to <code>TARG</code> onto the stack&quot;. At the end of the operation, the stack does not contain the values 10 and 20, but actually contains two pointers to <code>TARG</code>, which we have set to 20.</p>

<p>If you need to push multiple different values then you should either use the <code>(X)PUSHs</code> macros, or else use the new <code>m(X)PUSH[iunp]</code> macros, none of which make use of <code>TARG</code>. The <code>(X)PUSHs</code> macros simply push an SV* on the stack, which, as noted under <a href="perlguts.html#XSUBs-and-the-Argument-Stack">&quot;XSUBs and the Argument Stack&quot;</a>, will often need to be &quot;mortal&quot;. The new <code>m(X)PUSH[iunp]</code> macros make this a little easier to achieve by creating a new mortal for you (via <code>(X)PUSHmortal</code>), pushing that onto the stack (extending it if necessary in the case of the <code>mXPUSH[iunp]</code> macros), and then setting its value. Thus, instead of writing this to &quot;fix&quot; the example above:</p>

<pre><code class="plaintext">XPUSHs(sv_2mortal(newSViv(10)))
XPUSHs(sv_2mortal(newSViv(20)))</code></pre>

<p>you can simply write:</p>

<pre><code class="plaintext">mXPUSHi(10)
mXPUSHi(20)</code></pre>

<p>On a related note, if you do use <code>(X)PUSH[iunp]</code>, then you&#39;re going to need a <code>dTARG</code> in your variable declarations so that the <code>*PUSH*</code> macros can make use of the local variable <code>TARG</code>. See also <code>dTARGET</code> and <code>dXSTARG</code>.</p>

<h2 id="Scratchpads"><a class="permalink" href="perlguts.html#Scratchpads">#</a>Scratchpads</h2>

<p>The question remains on when the SVs which are <i>target</i>s for opcodes are created. The answer is that they are created when the current unit--a subroutine or a file (for opcodes for statements outside of subroutines)--is compiled. During this time a special anonymous Perl array is created, which is called a scratchpad for the current unit.</p>

<p>A scratchpad keeps SVs which are lexicals for the current unit and are targets for opcodes. A previous version of this document stated that one can deduce that an SV lives on a scratchpad by looking on its flags: lexicals have <code>SVs_PADMY</code> set, and <i>target</i>s have <code>SVs_PADTMP</code> set. But this has never been fully true. <code>SVs_PADMY</code> could be set on a variable that no longer resides in any pad. While <i>target</i>s do have <code>SVs_PADTMP</code> set, it can also be set on variables that have never resided in a pad, but nonetheless act like <i>target</i>s. As of perl 5.21.5, the <code>SVs_PADMY</code> flag is no longer used and is defined as 0. <code>SvPADMY()</code> now returns true for anything without <code>SVs_PADTMP</code>.</p>

<p>The correspondence between OPs and <i>target</i>s is not 1-to-1. Different OPs in the compile tree of the unit can use the same target, if this would not conflict with the expected life of the temporary.</p>

<h2 id="Scratchpads-and-recursion"><a class="permalink" href="perlguts.html#Scratchpads-and-recursion">#</a><a id="Scratchpads1"></a>Scratchpads and recursion</h2>

<p>In fact it is not 100% true that a compiled unit contains a pointer to the scratchpad AV. In fact it contains a pointer to an AV of (initially) one element, and this element is the scratchpad AV. Why do we need an extra level of indirection?</p>

<p>The answer is <b>recursion</b>, and maybe <b>threads</b>. Both these can create several execution pointers going into the same subroutine. For the subroutine-child not write over the temporaries for the subroutine-parent (lifespan of which covers the call to the child), the parent and the child should have different scratchpads. (<i>And</i> the lexicals should be separate anyway!)</p>

<p>So each subroutine is born with an array of scratchpads (of length 1). On each entry to the subroutine it is checked that the current depth of the recursion is not more than the length of this array, and if it is, new scratchpad is created and pushed into the array.</p>

<p>The <i>target</i>s on this scratchpad are <code>undef</code>s, but they are already marked with correct flags.</p>

<h1 id="Memory-Allocation"><a class="permalink" href="perlguts.html#Memory-Allocation">#</a><a id="Memory"></a>Memory Allocation</h1>

<h2 id="Allocation"><a class="permalink" href="perlguts.html#Allocation">#</a>Allocation</h2>

<p>All memory meant to be used with the Perl API functions should be manipulated using the macros described in this section. The macros provide the necessary transparency between differences in the actual malloc implementation that is used within perl.</p>

<p>The following three macros are used to initially allocate memory :</p>

<pre><code>Newx(pointer, number, type);
Newxc(pointer, number, type, cast);
Newxz(pointer, number, type);</code></pre>

<p>The first argument <code>pointer</code> should be the name of a variable that will point to the newly allocated memory.</p>

<p>The second and third arguments <code>number</code> and <code>type</code> specify how many of the specified type of data structure should be allocated. The argument <code>type</code> is passed to <code>sizeof</code>. The final argument to <code>Newxc</code>, <code>cast</code>, should be used if the <code>pointer</code> argument is different from the <code>type</code> argument.</p>

<p>Unlike the <code>Newx</code> and <code>Newxc</code> macros, the <code>Newxz</code> macro calls <code>memzero</code> to zero out all the newly allocated memory.</p>

<h2 id="Reallocation"><a class="permalink" href="perlguts.html#Reallocation">#</a>Reallocation</h2>

<pre><code>Renew(pointer, number, type);
Renewc(pointer, number, type, cast);
Safefree(pointer)</code></pre>

<p>These three macros are used to change a memory buffer size or to free a piece of memory no longer needed. The arguments to <code>Renew</code> and <code>Renewc</code> match those of <code>New</code> and <code>Newc</code> with the exception of not needing the &quot;magic cookie&quot; argument.</p>

<h2 id="Moving"><a class="permalink" href="perlguts.html#Moving">#</a>Moving</h2>

<pre><code>Move(source, dest, number, type);
Copy(source, dest, number, type);
Zero(dest, number, type);</code></pre>

<p>These three macros are used to move, copy, or zero out previously allocated memory. The <code>source</code> and <code>dest</code> arguments point to the source and destination starting points. Perl will move, copy, or zero out <code>number</code> instances of the size of the <code>type</code> data structure (using the <code>sizeof</code> function).</p>

<h1 id="PerlIO"><a class="permalink" href="perlguts.html#PerlIO">#</a>PerlIO</h1>

<p>The most recent development releases of Perl have been experimenting with removing Perl&#39;s dependency on the &quot;normal&quot; standard I/O suite and allowing other stdio implementations to be used. This involves creating a new abstraction layer that then calls whichever implementation of stdio Perl was compiled with. All XSUBs should now use the functions in the PerlIO abstraction layer and not make any assumptions about what kind of stdio is being used.</p>

<p>For a complete description of the PerlIO abstraction, consult <a href="perlapio.html">perlapio</a>.</p>

<h1 id="Compiled-code"><a class="permalink" href="perlguts.html#Compiled-code">#</a><a id="Compiled"></a>Compiled code</h1>

<h2 id="Code-tree"><a class="permalink" href="perlguts.html#Code-tree">#</a><a id="Code"></a>Code tree</h2>

<p>Here we describe the internal form your code is converted to by Perl. Start with a simple example:</p>

<pre><code>$a = $b + $c;</code></pre>

<p>This is converted to a tree similar to this one:</p>

<pre><code>       assign-to
     /           \
    +             $a
  /   \
$b     $c</code></pre>

<p>(but slightly more complicated). This tree reflects the way Perl parsed your code, but has nothing to do with the execution order. There is an additional &quot;thread&quot; going through the nodes of the tree which shows the order of execution of the nodes. In our simplified example above it looks like:</p>

<pre><code>$b ---&gt; $c ---&gt; + ---&gt; $a ---&gt; assign-to</code></pre>

<p>But with the actual compile tree for <code>$a = $b + $c</code> it is different: some nodes <i>optimized away</i>. As a corollary, though the actual tree contains more nodes than our simplified example, the execution order is the same as in our example.</p>

<h2 id="Examining-the-tree"><a class="permalink" href="perlguts.html#Examining-the-tree">#</a><a id="Examining"></a>Examining the tree</h2>

<p>If you have your perl compiled for debugging (usually done with <code>-DDEBUGGING</code> on the <code>Configure</code> command line), you may examine the compiled tree by specifying <code>-Dx</code> on the Perl command line. The output takes several lines per node, and for <code>$b+$c</code> it looks like this:</p>

<pre><code>5           TYPE = add  ===&gt; 6
            TARG = 1
            FLAGS = (SCALAR,KIDS)
            {
                TYPE = null  ===&gt; (4)
                  (was rv2sv)
                FLAGS = (SCALAR,KIDS)
                {
3                   TYPE = gvsv  ===&gt; 4
                    FLAGS = (SCALAR)
                    GV = main::b
                }
            }
            {
                TYPE = null  ===&gt; (5)
                  (was rv2sv)
                FLAGS = (SCALAR,KIDS)
                {
4                   TYPE = gvsv  ===&gt; 5
                    FLAGS = (SCALAR)
                    GV = main::c
                }
            }</code></pre>

<p>This tree has 5 nodes (one per <code>TYPE</code> specifier), only 3 of them are not optimized away (one per number in the left column). The immediate children of the given node correspond to <code>{}</code> pairs on the same level of indentation, thus this listing corresponds to the tree:</p>

<pre><code class="plaintext">    add
  /     \
null    null
 |       |
gvsv    gvsv</code></pre>

<p>The execution order is indicated by <code>===&gt;</code> marks, thus it is <code>3 4 5 6</code> (node <code>6</code> is not included into above listing), i.e., <code>gvsv gvsv add whatever</code>.</p>

<p>Each of these nodes represents an op, a fundamental operation inside the Perl core. The code which implements each operation can be found in the <i>pp*.c</i> files; the function which implements the op with type <code>gvsv</code> is <code>pp_gvsv</code>, and so on. As the tree above shows, different ops have different numbers of children: <code>add</code> is a binary operator, as one would expect, and so has two children. To accommodate the various different numbers of children, there are various types of op data structure, and they link together in different ways.</p>

<p>The simplest type of op structure is <code>OP</code>: this has no children. Unary operators, <code>UNOP</code>s, have one child, and this is pointed to by the <code>op_first</code> field. Binary operators (<code>BINOP</code>s) have not only an <code>op_first</code> field but also an <code>op_last</code> field. The most complex type of op is a <code>LISTOP</code>, which has any number of children. In this case, the first child is pointed to by <code>op_first</code> and the last child by <code>op_last</code>. The children in between can be found by iteratively following the <code>OpSIBLING</code> pointer from the first child to the last (but see below).</p>

<p>There are also some other op types: a <code>PMOP</code> holds a regular expression, and has no children, and a <code>LOOP</code> may or may not have children. If the <code>op_children</code> field is non-zero, it behaves like a <code>LISTOP</code>. To complicate matters, if a <code>UNOP</code> is actually a <code>null</code> op after optimization (see <a href="perlguts.html#Compile-pass-2%3A-context-propagation">&quot;Compile pass 2: context propagation&quot;</a>) it will still have children in accordance with its former type.</p>

<p>Finally, there is a <code>LOGOP</code>, or logic op. Like a <code>LISTOP</code>, this has one or more children, but it doesn&#39;t have an <code>op_last</code> field: so you have to follow <code>op_first</code> and then the <code>OpSIBLING</code> chain itself to find the last child. Instead it has an <code>op_other</code> field, which is comparable to the <code>op_next</code> field described below, and represents an alternate execution path. Operators like <code>and</code>, <code>or</code> and <code>?</code> are <code>LOGOP</code>s. Note that in general, <code>op_other</code> may not point to any of the direct children of the <code>LOGOP</code>.</p>

<p>Starting in version 5.21.2, perls built with the experimental define <code>-DPERL_OP_PARENT</code> add an extra boolean flag for each op, <code>op_moresib</code>. When not set, this indicates that this is the last op in an <code>OpSIBLING</code> chain. This frees up the <code>op_sibling</code> field on the last sibling to point back to the parent op. Under this build, that field is also renamed <code>op_sibparent</code> to reflect its joint role. The macro <code>OpSIBLING(o)</code> wraps this special behaviour, and always returns NULL on the last sibling. With this build the <code>op_parent(o)</code> function can be used to find the parent of any op. Thus for forward compatibility, you should always use the <code>OpSIBLING(o)</code> macro rather than accessing <code>op_sibling</code> directly.</p>

<p>Another way to examine the tree is to use a compiler back-end module, such as <a href="./B::Concise.html">B::Concise</a>.</p>

<h2 id="Compile-pass-1:-check-routines"><a class="permalink" href="perlguts.html#Compile-pass-1:-check-routines">#</a><a id="Compile"></a>Compile pass 1: check routines</h2>

<p>The tree is created by the compiler while <i>yacc</i> code feeds it the constructions it recognizes. Since <i>yacc</i> works bottom-up, so does the first pass of perl compilation.</p>

<p>What makes this pass interesting for perl developers is that some optimization may be performed on this pass. This is optimization by so-called &quot;check routines&quot;. The correspondence between node names and corresponding check routines is described in <i>opcode.pl</i> (do not forget to run <code>make regen_headers</code> if you modify this file).</p>

<p>A check routine is called when the node is fully constructed except for the execution-order thread. Since at this time there are no back-links to the currently constructed node, one can do most any operation to the top-level node, including freeing it and/or creating new nodes above/below it.</p>

<p>The check routine returns the node which should be inserted into the tree (if the top-level node was not modified, check routine returns its argument).</p>

<p>By convention, check routines have names <code>ck_*</code>. They are usually called from <code>new*OP</code> subroutines (or <code>convert</code>) (which in turn are called from <i>perly.y</i>).</p>

<h2 id="Compile-pass-1a:-constant-folding"><a class="permalink" href="perlguts.html#Compile-pass-1a:-constant-folding">#</a><a id="Compile1"></a>Compile pass 1a: constant folding</h2>

<p>Immediately after the check routine is called the returned node is checked for being compile-time executable. If it is (the value is judged to be constant) it is immediately executed, and a <i>constant</i> node with the &quot;return value&quot; of the corresponding subtree is substituted instead. The subtree is deleted.</p>

<p>If constant folding was not performed, the execution-order thread is created.</p>

<h2 id="Compile-pass-2:-context-propagation"><a class="permalink" href="perlguts.html#Compile-pass-2:-context-propagation">#</a><a id="Compile2"></a>Compile pass 2: context propagation</h2>

<p>When a context for a part of compile tree is known, it is propagated down through the tree. At this time the context can have 5 values (instead of 2 for runtime context): void, boolean, scalar, list, and lvalue. In contrast with the pass 1 this pass is processed from top to bottom: a node&#39;s context determines the context for its children.</p>

<p>Additional context-dependent optimizations are performed at this time. Since at this moment the compile tree contains back-references (via &quot;thread&quot; pointers), nodes cannot be free()d now. To allow optimized-away nodes at this stage, such nodes are null()ified instead of free()ing (i.e. their type is changed to OP_NULL).</p>

<h2 id="Compile-pass-3:-peephole-optimization"><a class="permalink" href="perlguts.html#Compile-pass-3:-peephole-optimization">#</a><a id="Compile3"></a>Compile pass 3: peephole optimization</h2>

<p>After the compile tree for a subroutine (or for an <code>eval</code> or a file) is created, an additional pass over the code is performed. This pass is neither top-down or bottom-up, but in the execution order (with additional complications for conditionals). Optimizations performed at this stage are subject to the same restrictions as in the pass 2.</p>

<p>Peephole optimizations are done by calling the function pointed to by the global variable <code>PL_peepp</code>. By default, <code>PL_peepp</code> just calls the function pointed to by the global variable <code>PL_rpeepp</code>. By default, that performs some basic op fixups and optimisations along the execution-order op chain, and recursively calls <code>PL_rpeepp</code> for each side chain of ops (resulting from conditionals). Extensions may provide additional optimisations or fixups, hooking into either the per-subroutine or recursive stage, like this:</p>

<pre><code>static peep_t prev_peepp;
static void my_peep(pTHX_ OP *o)
{
    /* custom per-subroutine optimisation goes here */
    prev_peepp(aTHX_ o);
    /* custom per-subroutine optimisation may also go here */
}
BOOT:
    prev_peepp = PL_peepp;
    PL_peepp = my_peep;

static peep_t prev_rpeepp;
static void my_rpeep(pTHX_ OP *first)
{
    OP *o = first, *t = first;
    for(; o = o-&gt;op_next, t = t-&gt;op_next) {
        /* custom per-op optimisation goes here */
        o = o-&gt;op_next;
        if (!o || o == t) break;
        /* custom per-op optimisation goes AND here */
    }
    prev_rpeepp(aTHX_ orig_o);
}
BOOT:
    prev_rpeepp = PL_rpeepp;
    PL_rpeepp = my_rpeep;</code></pre>

<h2 id="Pluggable-runops"><a class="permalink" href="perlguts.html#Pluggable-runops">#</a><a id="Pluggable"></a>Pluggable runops</h2>

<p>The compile tree is executed in a runops function. There are two runops functions, in <i>run.c</i> and in <i>dump.c</i>. <code>Perl_runops_debug</code> is used with DEBUGGING and <code>Perl_runops_standard</code> is used otherwise. For fine control over the execution of the compile tree it is possible to provide your own runops function.</p>

<p>It&#39;s probably best to copy one of the existing runops functions and change it to suit your needs. Then, in the BOOT section of your XS file, add the line:</p>

<pre><code>PL_runops = my_runops;</code></pre>

<p>This function should be as efficient as possible to keep your programs running as fast as possible.</p>

<h2 id="Compile-time-scope-hooks"><a class="permalink" href="perlguts.html#Compile-time-scope-hooks">#</a><a id="Compile4"></a>Compile-time scope hooks</h2>

<p>As of perl 5.14 it is possible to hook into the compile-time lexical scope mechanism using <code>Perl_blockhook_register</code>. This is used like this:</p>

<pre><code>STATIC void my_start_hook(pTHX_ int full);
STATIC BHK my_hooks;

BOOT:
    BhkENTRY_set(&amp;my_hooks, bhk_start, my_start_hook);
    Perl_blockhook_register(aTHX_ &amp;my_hooks);</code></pre>

<p>This will arrange to have <code>my_start_hook</code> called at the start of compiling every lexical scope. The available hooks are:</p>

<dl>

<dt id="void-bhk_start(pTHX_-int-full)"><a class="permalink" href="perlguts.html#void-bhk_start(pTHX_-int-full)">#</a><a id="void4"></a><a id="void-bhk_start-pTHX_-int-full"></a><code>void bhk_start(pTHX_ int full)</code></dt>
<dd>

<p>This is called just after starting a new lexical scope. Note that Perl code like</p>

<pre><code>if ($x) { ... }</code></pre>

<p>creates two scopes: the first starts at the <code>(</code> and has <code>full == 1</code>, the second starts at the <code>{</code> and has <code>full == 0</code>. Both end at the <code>}</code>, so calls to <code>start</code> and <code>pre</code>/<code>post_end</code> will match. Anything pushed onto the save stack by this hook will be popped just before the scope ends (between the <code>pre_</code> and <code>post_end</code> hooks, in fact).</p>

</dd>
<dt id="void-bhk_pre_end(pTHX_-OP-**o)"><a class="permalink" href="perlguts.html#void-bhk_pre_end(pTHX_-OP-**o)">#</a><a id="void5"></a><a id="void-bhk_pre_end-pTHX_-OP-o"></a><code>void bhk_pre_end(pTHX_ OP **o)</code></dt>
<dd>

<p>This is called at the end of a lexical scope, just before unwinding the stack. <i>o</i> is the root of the optree representing the scope; it is a double pointer so you can replace the OP if you need to.</p>

</dd>
<dt id="void-bhk_post_end(pTHX_-OP-**o)"><a class="permalink" href="perlguts.html#void-bhk_post_end(pTHX_-OP-**o)">#</a><a id="void6"></a><a id="void-bhk_post_end-pTHX_-OP-o"></a><code>void bhk_post_end(pTHX_ OP **o)</code></dt>
<dd>

<p>This is called at the end of a lexical scope, just after unwinding the stack. <i>o</i> is as above. Note that it is possible for calls to <code>pre_</code> and <code>post_end</code> to nest, if there is something on the save stack that calls string eval.</p>

</dd>
<dt id="void-bhk_eval(pTHX_-OP-*const-o)"><a class="permalink" href="perlguts.html#void-bhk_eval(pTHX_-OP-*const-o)">#</a><a id="void7"></a><a id="void-bhk_eval-pTHX_-OP-const-o"></a><code>void bhk_eval(pTHX_ OP *const o)</code></dt>
<dd>

<p>This is called just before starting to compile an <code>eval STRING</code>, <code>do FILE</code>, <code>require</code> or <code>use</code>, after the eval has been set up. <i>o</i> is the OP that requested the eval, and will normally be an <code>OP_ENTEREVAL</code>, <code>OP_DOFILE</code> or <code>OP_REQUIRE</code>.</p>

</dd>
</dl>

<p>Once you have your hook functions, you need a <code>BHK</code> structure to put them in. It&#39;s best to allocate it statically, since there is no way to free it once it&#39;s registered. The function pointers should be inserted into this structure using the <code>BhkENTRY_set</code> macro, which will also set flags indicating which entries are valid. If you do need to allocate your <code>BHK</code> dynamically for some reason, be sure to zero it before you start.</p>

<p>Once registered, there is no mechanism to switch these hooks off, so if that is necessary you will need to do this yourself. An entry in <code>%^H</code> is probably the best way, so the effect is lexically scoped; however it is also possible to use the <code>BhkDISABLE</code> and <code>BhkENABLE</code> macros to temporarily switch entries on and off. You should also be aware that generally speaking at least one scope will have opened before your extension is loaded, so you will see some <code>pre</code>/<code>post_end</code> pairs that didn&#39;t have a matching <code>start</code>.</p>

<h1 id="Examining-internal-data-structures-with-the-dump-functions"><a class="permalink" href="perlguts.html#Examining-internal-data-structures-with-the-dump-functions">#</a><a id="Examining1"></a>Examining internal data structures with the <code>dump</code> functions</h1>

<p>To aid debugging, the source file <i>dump.c</i> contains a number of functions which produce formatted output of internal data structures.</p>

<p>The most commonly used of these functions is <code>Perl_sv_dump</code>; it&#39;s used for dumping SVs, AVs, HVs, and CVs. The <code>Devel::Peek</code> module calls <code>sv_dump</code> to produce debugging output from Perl-space, so users of that module should already be familiar with its format.</p>

<p><code>Perl_op_dump</code> can be used to dump an <code>OP</code> structure or any of its derivatives, and produces output similar to <code>perl -Dx</code>; in fact, <code>Perl_dump_eval</code> will dump the main root of the code being evaluated, exactly like <code>-Dx</code>.</p>

<p>Other useful functions are <code>Perl_dump_sub</code>, which turns a <code>GV</code> into an op tree, <code>Perl_dump_packsubs</code> which calls <code>Perl_dump_sub</code> on all the subroutines in a package like so: (Thankfully, these are all xsubs, so there is no op tree)</p>

<pre><code class="plaintext">(gdb) print Perl_dump_packsubs(PL_defstash)

SUB attributes::bootstrap = (xsub 0x811fedc 0)

SUB UNIVERSAL::can = (xsub 0x811f50c 0)

SUB UNIVERSAL::isa = (xsub 0x811f304 0)

SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)

SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)</code></pre>

<p>and <code>Perl_dump_all</code>, which dumps all the subroutines in the stash and the op tree of the main root.</p>

<h1 id="How-multiple-interpreters-and-concurrency-are-supported"><a class="permalink" href="perlguts.html#How-multiple-interpreters-and-concurrency-are-supported">#</a><a id="How"></a>How multiple interpreters and concurrency are supported</h1>

<h2 id="Background-and-PERL_IMPLICIT_CONTEXT"><a class="permalink" href="perlguts.html#Background-and-PERL_IMPLICIT_CONTEXT">#</a><a id="Background"></a>Background and PERL_IMPLICIT_CONTEXT</h2>

<p>The Perl interpreter can be regarded as a closed box: it has an API for feeding it code or otherwise making it do things, but it also has functions for its own use. This smells a lot like an object, and there is a way for you to build Perl so that you can have multiple interpreters, with one interpreter represented either as a C structure, or inside a thread-specific structure. These structures contain all the context, the state of that interpreter.</p>

<p>The macro that controls the major Perl build flavor is MULTIPLICITY. The MULTIPLICITY build has a C structure that packages all the interpreter state. With multiplicity-enabled perls, PERL_IMPLICIT_CONTEXT is also normally defined, and enables the support for passing in a &quot;hidden&quot; first argument that represents all three data structures. MULTIPLICITY makes multi-threaded perls possible (with the ithreads threading model, related to the macro USE_ITHREADS.)</p>

<p>To see whether you have non-const data you can use a BSD (or GNU) compatible <code>nm</code>:</p>

<pre><code class="plaintext">nm libperl.a | grep -v &#39; [TURtr] &#39;</code></pre>

<p>If this displays any <code>D</code> or <code>d</code> symbols (or possibly <code>C</code> or <code>c</code>), you have non-const data. The symbols the <code>grep</code> removed are as follows: <code>Tt</code> are <i>text</i>, or code, the <code>Rr</code> are <i>read-only</i> (const) data, and the <code>U</code> is &lt;undefined&gt;, external symbols referred to.</p>

<p>The test <i>t/porting/libperl.t</i> does this kind of symbol sanity checking on <code>libperl.a</code>.</p>

<p>All this obviously requires a way for the Perl internal functions to be either subroutines taking some kind of structure as the first argument, or subroutines taking nothing as the first argument. To enable these two very different ways of building the interpreter, the Perl source (as it does in so many other situations) makes heavy use of macros and subroutine naming conventions.</p>

<p>First problem: deciding which functions will be public API functions and which will be private. All functions whose names begin <code>S_</code> are private (think &quot;S&quot; for &quot;secret&quot; or &quot;static&quot;). All other functions begin with &quot;Perl_&quot;, but just because a function begins with &quot;Perl_&quot; does not mean it is part of the API. (See <a href="perlguts.html#Internal-Functions">&quot;Internal Functions&quot;</a>.) The easiest way to be <b>sure</b> a function is part of the API is to find its entry in <a href="perlapi.html">perlapi</a>. If it exists in <a href="perlapi.html">perlapi</a>, it&#39;s part of the API. If it doesn&#39;t, and you think it should be (i.e., you need it for your extension), submit an issue at <a href="https://github.com/Perl/perl5/issues">https://github.com/Perl/perl5/issues</a> explaining why you think it should be.</p>

<p>Second problem: there must be a syntax so that the same subroutine declarations and calls can pass a structure as their first argument, or pass nothing. To solve this, the subroutines are named and declared in a particular way. Here&#39;s a typical start of a static function used within the Perl guts:</p>

<pre><code class="plaintext">STATIC void
S_incline(pTHX_ char *s)</code></pre>

<p>STATIC becomes &quot;static&quot; in C, and may be #define&#39;d to nothing in some configurations in the future.</p>

<p>A public function (i.e. part of the internal API, but not necessarily sanctioned for use in extensions) begins like this:</p>

<pre><code class="plaintext">void
Perl_sv_setiv(pTHX_ SV* dsv, IV num)</code></pre>

<p><code>pTHX_</code> is one of a number of macros (in <i>perl.h</i>) that hide the details of the interpreter&#39;s context. THX stands for &quot;thread&quot;, &quot;this&quot;, or &quot;thingy&quot;, as the case may be. (And no, George Lucas is not involved. :-) The first character could be &#39;p&#39; for a <b>p</b>rototype, &#39;a&#39; for <b>a</b>rgument, or &#39;d&#39; for <b>d</b>eclaration, so we have <code>pTHX</code>, <code>aTHX</code> and <code>dTHX</code>, and their variants.</p>

<p>When Perl is built without options that set PERL_IMPLICIT_CONTEXT, there is no first argument containing the interpreter&#39;s context. The trailing underscore in the pTHX_ macro indicates that the macro expansion needs a comma after the context argument because other arguments follow it. If PERL_IMPLICIT_CONTEXT is not defined, pTHX_ will be ignored, and the subroutine is not prototyped to take the extra argument. The form of the macro without the trailing underscore is used when there are no additional explicit arguments.</p>

<p>When a core function calls another, it must pass the context. This is normally hidden via macros. Consider <code>sv_setiv</code>. It expands into something like this:</p>

<pre><code class="plaintext">#ifdef PERL_IMPLICIT_CONTEXT
  #define sv_setiv(a,b)      Perl_sv_setiv(aTHX_ a, b)
  /* can&#39;t do this for vararg functions, see below */
#else
  #define sv_setiv           Perl_sv_setiv
#endif</code></pre>

<p>This works well, and means that XS authors can gleefully write:</p>

<pre><code>sv_setiv(foo, bar);</code></pre>

<p>and still have it work under all the modes Perl could have been compiled with.</p>

<p>This doesn&#39;t work so cleanly for varargs functions, though, as macros imply that the number of arguments is known in advance. Instead we either need to spell them out fully, passing <code>aTHX_</code> as the first argument (the Perl core tends to do this with functions like Perl_warner), or use a context-free version.</p>

<p>The context-free version of Perl_warner is called Perl_warner_nocontext, and does not take the extra argument. Instead it does <code>dTHX;</code> to get the context from thread-local storage. We <code>#define warner Perl_warner_nocontext</code> so that extensions get source compatibility at the expense of performance. (Passing an arg is cheaper than grabbing it from thread-local storage.)</p>

<p>You can ignore [pad]THXx when browsing the Perl headers/sources. Those are strictly for use within the core. Extensions and embedders need only be aware of [pad]THX.</p>

<h2 id="So-what-happened-to-dTHR?"><a class="permalink" href="perlguts.html#So-what-happened-to-dTHR?">#</a><a id="So"></a><a id="So-what-happened-to-dTHR"></a>So what happened to dTHR?</h2>

<p><code>dTHR</code> was introduced in perl 5.005 to support the older thread model. The older thread model now uses the <code>THX</code> mechanism to pass context pointers around, so <code>dTHR</code> is not useful any more. Perl 5.6.0 and later still have it for backward source compatibility, but it is defined to be a no-op.</p>

<h2 id="How-do-I-use-all-this-in-extensions?"><a class="permalink" href="perlguts.html#How-do-I-use-all-this-in-extensions?">#</a><a id="How1"></a><a id="How-do-I-use-all-this-in-extensions"></a>How do I use all this in extensions?</h2>

<p>When Perl is built with PERL_IMPLICIT_CONTEXT, extensions that call any functions in the Perl API will need to pass the initial context argument somehow. The kicker is that you will need to write it in such a way that the extension still compiles when Perl hasn&#39;t been built with PERL_IMPLICIT_CONTEXT enabled.</p>

<p>There are three ways to do this. First, the easy but inefficient way, which is also the default, in order to maintain source compatibility with extensions: whenever <i>XSUB.h</i> is #included, it redefines the aTHX and aTHX_ macros to call a function that will return the context. Thus, something like:</p>

<pre><code>sv_setiv(sv, num);</code></pre>

<p>in your extension will translate to this when PERL_IMPLICIT_CONTEXT is in effect:</p>

<pre><code>Perl_sv_setiv(Perl_get_context(), sv, num);</code></pre>

<p>or to this otherwise:</p>

<pre><code>Perl_sv_setiv(sv, num);</code></pre>

<p>You don&#39;t have to do anything new in your extension to get this; since the Perl library provides Perl_get_context(), it will all just work.</p>

<p>The second, more efficient way is to use the following template for your Foo.xs:</p>

<pre><code>#define PERL_NO_GET_CONTEXT     /* we want efficiency */
#include &quot;EXTERN.h&quot;
#include &quot;perl.h&quot;
#include &quot;XSUB.h&quot;

STATIC void my_private_function(int arg1, int arg2);

STATIC void
my_private_function(int arg1, int arg2)
{
    dTHX;       /* fetch context */
    ... call many Perl API functions ...
}

[... etc ...]

MODULE = Foo            PACKAGE = Foo

/* typical XSUB */

void
my_xsub(arg)
        int arg
    CODE:
        my_private_function(arg, 10);</code></pre>

<p>Note that the only two changes from the normal way of writing an extension is the addition of a <code>#define PERL_NO_GET_CONTEXT</code> before including the Perl headers, followed by a <code>dTHX;</code> declaration at the start of every function that will call the Perl API. (You&#39;ll know which functions need this, because the C compiler will complain that there&#39;s an undeclared identifier in those functions.) No changes are needed for the XSUBs themselves, because the XS() macro is correctly defined to pass in the implicit context if needed.</p>

<p>The third, even more efficient way is to ape how it is done within the Perl guts:</p>

<pre><code>#define PERL_NO_GET_CONTEXT     /* we want efficiency */
#include &quot;EXTERN.h&quot;
#include &quot;perl.h&quot;
#include &quot;XSUB.h&quot;

/* pTHX_ only needed for functions that call Perl API */
STATIC void my_private_function(pTHX_ int arg1, int arg2);

STATIC void
my_private_function(pTHX_ int arg1, int arg2)
{
    /* dTHX; not needed here, because THX is an argument */
    ... call Perl API functions ...
}

[... etc ...]

MODULE = Foo            PACKAGE = Foo

/* typical XSUB */

void
my_xsub(arg)
        int arg
    CODE:
        my_private_function(aTHX_ arg, 10);</code></pre>

<p>This implementation never has to fetch the context using a function call, since it is always passed as an extra argument. Depending on your needs for simplicity or efficiency, you may mix the previous two approaches freely.</p>

<p>Never add a comma after <code>pTHX</code> yourself--always use the form of the macro with the underscore for functions that take explicit arguments, or the form without the argument for functions with no explicit arguments.</p>

<h2 id="Should-I-do-anything-special-if-I-call-perl-from-multiple-threads?"><a class="permalink" href="perlguts.html#Should-I-do-anything-special-if-I-call-perl-from-multiple-threads?">#</a><a id="Should"></a><a id="Should-I-do-anything-special-if-I-call-perl-from-multiple-threads"></a>Should I do anything special if I call perl from multiple threads?</h2>

<p>If you create interpreters in one thread and then proceed to call them in another, you need to make sure perl&#39;s own Thread Local Storage (TLS) slot is initialized correctly in each of those threads.</p>

<p>The <code>perl_alloc</code> and <code>perl_clone</code> API functions will automatically set the TLS slot to the interpreter they created, so that there is no need to do anything special if the interpreter is always accessed in the same thread that created it, and that thread did not create or call any other interpreters afterwards. If that is not the case, you have to set the TLS slot of the thread before calling any functions in the Perl API on that particular interpreter. This is done by calling the <code>PERL_SET_CONTEXT</code> macro in that thread as the first thing you do:</p>

<pre><code>/* do this before doing anything else with some_perl */
PERL_SET_CONTEXT(some_perl);

... other Perl API calls on some_perl go here ...</code></pre>

<h2 id="Future-Plans-and-PERL_IMPLICIT_SYS"><a class="permalink" href="perlguts.html#Future-Plans-and-PERL_IMPLICIT_SYS">#</a><a id="Future"></a>Future Plans and PERL_IMPLICIT_SYS</h2>

<p>Just as PERL_IMPLICIT_CONTEXT provides a way to bundle up everything that the interpreter knows about itself and pass it around, so too are there plans to allow the interpreter to bundle up everything it knows about the environment it&#39;s running on. This is enabled with the PERL_IMPLICIT_SYS macro. Currently it only works with USE_ITHREADS on Windows.</p>

<p>This allows the ability to provide an extra pointer (called the &quot;host&quot; environment) for all the system calls. This makes it possible for all the system stuff to maintain their own state, broken down into seven C structures. These are thin wrappers around the usual system calls (see <i>win32/perllib.c</i>) for the default perl executable, but for a more ambitious host (like the one that would do fork() emulation) all the extra work needed to pretend that different interpreters are actually different &quot;processes&quot;, would be done here.</p>

<p>The Perl engine/interpreter and the host are orthogonal entities. There could be one or more interpreters in a process, and one or more &quot;hosts&quot;, with free association between them.</p>

<h1 id="Internal-Functions"><a class="permalink" href="perlguts.html#Internal-Functions">#</a><a id="Internal"></a>Internal Functions</h1>

<p>All of Perl&#39;s internal functions which will be exposed to the outside world are prefixed by <code>Perl_</code> so that they will not conflict with XS functions or functions used in a program in which Perl is embedded. Similarly, all global variables begin with <code>PL_</code>. (By convention, static functions start with <code>S_</code>.)</p>

<p>Inside the Perl core (<code>PERL_CORE</code> defined), you can get at the functions either with or without the <code>Perl_</code> prefix, thanks to a bunch of defines that live in <i>embed.h</i>. Note that extension code should <i>not</i> set <code>PERL_CORE</code>; this exposes the full perl internals, and is likely to cause breakage of the XS in each new perl release.</p>

<p>The file <i>embed.h</i> is generated automatically from <i>embed.pl</i> and <i>embed.fnc</i>. <i>embed.pl</i> also creates the prototyping header files for the internal functions, generates the documentation and a lot of other bits and pieces. It&#39;s important that when you add a new function to the core or change an existing one, you change the data in the table in <i>embed.fnc</i> as well. Here&#39;s a sample entry from that table:</p>

<pre><code class="plaintext">Apd |SV**   |av_fetch   |AV* ar|I32 key|I32 lval</code></pre>

<p>The first column is a set of flags, the second column the return type, the third column the name. Columns after that are the arguments. The flags are documented at the top of <i>embed.fnc</i>.</p>

<p>If you edit <i>embed.pl</i> or <i>embed.fnc</i>, you will need to run <code>make regen_headers</code> to force a rebuild of <i>embed.h</i> and other auto-generated files.</p>

<h2 id="Formatted-Printing-of-IVs,-UVs,-and-NVs"><a class="permalink" href="perlguts.html#Formatted-Printing-of-IVs,-UVs,-and-NVs">#</a><a id="Formatted"></a><a id="Formatted-Printing-of-IVs-UVs-and-NVs"></a>Formatted Printing of IVs, UVs, and NVs</h2>

<p>If you are printing IVs, UVs, or NVS instead of the stdio(3) style formatting codes like <code>%d</code>, <code>%ld</code>, <code>%f</code>, you should use the following macros for portability</p>

<pre><code>IVdf            IV in decimal
UVuf            UV in decimal
UVof            UV in octal
UVxf            UV in hexadecimal
NVef            NV %e-like
NVff            NV %f-like
NVgf            NV %g-like</code></pre>

<p>These will take care of 64-bit integers and long doubles. For example:</p>

<pre><code>printf(&quot;IV is %&quot; IVdf &quot;\n&quot;, iv);</code></pre>

<p>The <code>IVdf</code> will expand to whatever is the correct format for the IVs. Note that the spaces are required around the format in case the code is compiled with C++, to maintain compliance with its standard.</p>

<p>Note that there are different &quot;long doubles&quot;: Perl will use whatever the compiler has.</p>

<p>If you are printing addresses of pointers, use %p or UVxf combined with PTR2UV().</p>

<h2 id="Formatted-Printing-of-SVs"><a class="permalink" href="perlguts.html#Formatted-Printing-of-SVs">#</a><a id="Formatted1"></a>Formatted Printing of SVs</h2>

<p>The contents of SVs may be printed using the <code>SVf</code> format, like so:</p>

<pre><code class="plaintext">Perl_croak(aTHX_ &quot;This croaked because: %&quot; SVf &quot;\n&quot;, SVfARG(err_msg))</code></pre>

<p>where <code>err_msg</code> is an SV.</p>

<p>Not all scalar types are printable. Simple values certainly are: one of IV, UV, NV, or PV. Also, if the SV is a reference to some value, either it will be dereferenced and the value printed, or information about the type of that value and its address are displayed. The results of printing any other type of SV are undefined and likely to lead to an interpreter crash. NVs are printed using a <code>%g</code>-ish format.</p>

<p>Note that the spaces are required around the <code>SVf</code> in case the code is compiled with C++, to maintain compliance with its standard.</p>

<p>Note that any filehandle being printed to under UTF-8 must be expecting UTF-8 in order to get good results and avoid Wide-character warnings. One way to do this for typical filehandles is to invoke perl with the <code>-C</code>&gt; parameter. (See <a href="perlrun.html#-C-%5Bnumber%2Flist%5D">&quot;-C [number/list]&quot; in perlrun</a>.</p>

<p>You can use this to concatenate two scalars:</p>

<pre><code>SV *var1 = get_sv(&quot;var1&quot;, GV_ADD);
SV *var2 = get_sv(&quot;var2&quot;, GV_ADD);
SV *var3 = newSVpvf(&quot;var1=%&quot; SVf &quot; and var2=%&quot; SVf,
                    SVfARG(var1), SVfARG(var2));</code></pre>

<h2 id="Formatted-Printing-of-Strings"><a class="permalink" href="perlguts.html#Formatted-Printing-of-Strings">#</a><a id="Formatted2"></a>Formatted Printing of Strings</h2>

<p>If you just want the bytes printed in a 7bit NUL-terminated string, you can just use <code>%s</code> (assuming they are all really only 7bit). But if there is a possibility the value will be encoded as UTF-8 or contains bytes above <code>0x7F</code> (and therefore 8bit), you should instead use the <code>UTF8f</code> format. And as its parameter, use the <code>UTF8fARG()</code> macro:</p>

<pre><code>chr * msg;

/* U+2018: \xE2\x80\x98 LEFT SINGLE QUOTATION MARK
   U+2019: \xE2\x80\x99 RIGHT SINGLE QUOTATION MARK */
if (can_utf8)
  msg = &quot;\xE2\x80\x98Uses fancy quotes\xE2\x80\x99&quot;;
else
  msg = &quot;&#39;Uses simple quotes&#39;&quot;;

Perl_croak(aTHX_ &quot;The message is: %&quot; UTF8f &quot;\n&quot;,
                 UTF8fARG(can_utf8, strlen(msg), msg));</code></pre>

<p>The first parameter to <code>UTF8fARG</code> is a boolean: 1 if the string is in UTF-8; 0 if string is in native byte encoding (Latin1). The second parameter is the number of bytes in the string to print. And the third and final parameter is a pointer to the first byte in the string.</p>

<p>Note that any filehandle being printed to under UTF-8 must be expecting UTF-8 in order to get good results and avoid Wide-character warnings. One way to do this for typical filehandles is to invoke perl with the <code>-C</code>&gt; parameter. (See <a href="perlrun.html#-C-%5Bnumber%2Flist%5D">&quot;-C [number/list]&quot; in perlrun</a>.</p>

<h2 id="Formatted-Printing-of-Size_t-and-SSize_t"><a class="permalink" href="perlguts.html#Formatted-Printing-of-Size_t-and-SSize_t">#</a><a id="Formatted3"></a>Formatted Printing of <code>Size_t</code> and <code>SSize_t</code></h2>

<p>The most general way to do this is to cast them to a UV or IV, and print as in the <a href="perlguts.html#Formatted-Printing-of-IVs%2C-UVs%2C-and-NVs">previous section</a>.</p>

<p>But if you&#39;re using <code>PerlIO_printf()</code>, it&#39;s less typing and visual clutter to use the <code>%z</code> length modifier (for <i>siZe</i>):</p>

<pre><code>PerlIO_printf(&quot;STRLEN is %zu\n&quot;, len);</code></pre>

<p>This modifier is not portable, so its use should be restricted to <code>PerlIO_printf()</code>.</p>

<h2 id="Formatted-Printing-of-Ptrdiff_t,-intmax_t,-short-and-other-special-sizes"><a class="permalink" href="perlguts.html#Formatted-Printing-of-Ptrdiff_t,-intmax_t,-short-and-other-special-sizes">#</a><a id="Formatted4"></a><a id="Formatted-Printing-of-Ptrdiff_t-intmax_t-short-and-other-special-sizes"></a>Formatted Printing of <code>Ptrdiff_t</code>, <code>intmax_t</code>, <code>short</code> and other special sizes</h2>

<p>There are modifiers for these special situations if you are using <code>PerlIO_printf()</code>. See <a href="perlfunc.html#size">&quot;size&quot; in perlfunc</a>.</p>

<h2 id="Pointer-To-Integer-and-Integer-To-Pointer"><a class="permalink" href="perlguts.html#Pointer-To-Integer-and-Integer-To-Pointer">#</a><a id="Pointer"></a>Pointer-To-Integer and Integer-To-Pointer</h2>

<p>Because pointer size does not necessarily equal integer size, use the follow macros to do it right.</p>

<pre><code class="plaintext">PTR2UV(pointer)
PTR2IV(pointer)
PTR2NV(pointer)
INT2PTR(pointertotype, integer)</code></pre>

<p>For example:</p>

<pre><code>IV  iv = ...;
SV *sv = INT2PTR(SV*, iv);</code></pre>

<p>and</p>

<pre><code>AV *av = ...;
UV  uv = PTR2UV(av);</code></pre>

<p>There are also</p>

<pre><code class="plaintext">PTR2nat(pointer)   /* pointer to integer of PTRSIZE */
PTR2ul(pointer)    /* pointer to unsigned long */</code></pre>

<p>And <code>PTRV</code> which gives the native type for an integer the same size as pointers, such as <code>unsigned</code> or <code>unsigned long</code>.</p>

<h2 id="Exception-Handling"><a class="permalink" href="perlguts.html#Exception-Handling">#</a><a id="Exception"></a>Exception Handling</h2>

<p>There are a couple of macros to do very basic exception handling in XS modules. You have to define <code>NO_XSLOCKS</code> before including <i>XSUB.h</i> to be able to use these macros:</p>

<pre><code class="plaintext">#define NO_XSLOCKS
#include &quot;XSUB.h&quot;</code></pre>

<p>You can use these macros if you call code that may croak, but you need to do some cleanup before giving control back to Perl. For example:</p>

<pre><code>dXCPT;    /* set up necessary variables */

XCPT_TRY_START {
  code_that_may_croak();
} XCPT_TRY_END

XCPT_CATCH
{
  /* do cleanup here */
  XCPT_RETHROW;
}</code></pre>

<p>Note that you always have to rethrow an exception that has been caught. Using these macros, it is not possible to just catch the exception and ignore it. If you have to ignore the exception, you have to use the <code>call_*</code> function.</p>

<p>The advantage of using the above macros is that you don&#39;t have to setup an extra function for <code>call_*</code>, and that using these macros is faster than using <code>call_*</code>.</p>

<h2 id="Source-Documentation"><a class="permalink" href="perlguts.html#Source-Documentation">#</a><a id="Source"></a>Source Documentation</h2>

<p>There&#39;s an effort going on to document the internal functions and automatically produce reference manuals from them -- <a href="perlapi.html">perlapi</a> is one such manual which details all the functions which are available to XS writers. <a href="perlintern.html">perlintern</a> is the autogenerated manual for the functions which are not part of the API and are supposedly for internal use only.</p>

<p>Source documentation is created by putting POD comments into the C source, like this:</p>

<pre><code class="plaintext">/*
=for apidoc sv_setiv

Copies an integer into the given SV.  Does not handle &#39;set&#39; magic.  See
L&lt;perlapi/sv_setiv_mg&gt;.

=cut
*/</code></pre>

<p>Please try and supply some documentation if you add functions to the Perl core.</p>

<h2 id="Backwards-compatibility"><a class="permalink" href="perlguts.html#Backwards-compatibility">#</a><a id="Backwards"></a>Backwards compatibility</h2>

<p>The Perl API changes over time. New functions are added or the interfaces of existing functions are changed. The <code>Devel::PPPort</code> module tries to provide compatibility code for some of these changes, so XS writers don&#39;t have to code it themselves when supporting multiple versions of Perl.</p>

<p><code>Devel::PPPort</code> generates a C header file <i>ppport.h</i> that can also be run as a Perl script. To generate <i>ppport.h</i>, run:</p>

<pre><code class="plaintext">perl -MDevel::PPPort -eDevel::PPPort::WriteFile</code></pre>

<p>Besides checking existing XS code, the script can also be used to retrieve compatibility information for various API calls using the <code>--api-info</code> command line switch. For example:</p>

<pre><code class="plaintext">% perl ppport.h --api-info=sv_magicext</code></pre>

<p>For details, see <code>perldoc ppport.h</code>.</p>

<h1 id="Unicode-Support"><a class="permalink" href="perlguts.html#Unicode-Support">#</a><a id="Unicode"></a>Unicode Support</h1>

<p>Perl 5.6.0 introduced Unicode support. It&#39;s important for porters and XS writers to understand this support and make sure that the code they write does not corrupt Unicode data.</p>

<h2 id="What-is-Unicode,-anyway?"><a class="permalink" href="perlguts.html#What-is-Unicode,-anyway?">#</a><a id="What2"></a><a id="What-is-Unicode-anyway"></a>What <b>is</b> Unicode, anyway?</h2>

<p>In the olden, less enlightened times, we all used to use ASCII. Most of us did, anyway. The big problem with ASCII is that it&#39;s American. Well, no, that&#39;s not actually the problem; the problem is that it&#39;s not particularly useful for people who don&#39;t use the Roman alphabet. What used to happen was that particular languages would stick their own alphabet in the upper range of the sequence, between 128 and 255. Of course, we then ended up with plenty of variants that weren&#39;t quite ASCII, and the whole point of it being a standard was lost.</p>

<p>Worse still, if you&#39;ve got a language like Chinese or Japanese that has hundreds or thousands of characters, then you really can&#39;t fit them into a mere 256, so they had to forget about ASCII altogether, and build their own systems using pairs of numbers to refer to one character.</p>

<p>To fix this, some people formed Unicode, Inc. and produced a new character set containing all the characters you can possibly think of and more. There are several ways of representing these characters, and the one Perl uses is called UTF-8. UTF-8 uses a variable number of bytes to represent a character. You can learn more about Unicode and Perl&#39;s Unicode model in <a href="perlunicode.html">perlunicode</a>.</p>

<p>(On EBCDIC platforms, Perl uses instead UTF-EBCDIC, which is a form of UTF-8 adapted for EBCDIC platforms. Below, we just talk about UTF-8. UTF-EBCDIC is like UTF-8, but the details are different. The macros hide the differences from you, just remember that the particular numbers and bit patterns presented below will differ in UTF-EBCDIC.)</p>

<h2 id="How-can-I-recognise-a-UTF-8-string?"><a class="permalink" href="perlguts.html#How-can-I-recognise-a-UTF-8-string?">#</a><a id="How2"></a><a id="How-can-I-recognise-a-UTF-8-string"></a>How can I recognise a UTF-8 string?</h2>

<p>You can&#39;t. This is because UTF-8 data is stored in bytes just like non-UTF-8 data. The Unicode character 200, (<code>0xC8</code> for you hex types) capital E with a grave accent, is represented by the two bytes <code>v196.172</code>. Unfortunately, the non-Unicode string <code>chr(196).chr(172)</code> has that byte sequence as well. So you can&#39;t tell just by looking -- this is what makes Unicode input an interesting problem.</p>

<p>In general, you either have to know what you&#39;re dealing with, or you have to guess. The API function <code>is_utf8_string</code> can help; it&#39;ll tell you if a string contains only valid UTF-8 characters, and the chances of a non-UTF-8 string looking like valid UTF-8 become very small very quickly with increasing string length. On a character-by-character basis, <code>isUTF8_CHAR</code> will tell you whether the current character in a string is valid UTF-8.</p>

<h2 id="How-does-UTF-8-represent-Unicode-characters?"><a class="permalink" href="perlguts.html#How-does-UTF-8-represent-Unicode-characters?">#</a><a id="How3"></a><a id="How-does-UTF-8-represent-Unicode-characters"></a>How does UTF-8 represent Unicode characters?</h2>

<p>As mentioned above, UTF-8 uses a variable number of bytes to store a character. Characters with values 0...127 are stored in one byte, just like good ol&#39; ASCII. Character 128 is stored as <code>v194.128</code>; this continues up to character 191, which is <code>v194.191</code>. Now we&#39;ve run out of bits (191 is binary <code>10111111</code>) so we move on; character 192 is <code>v195.128</code>. And so it goes on, moving to three bytes at character 2048. <a href="perlunicode.html#Unicode-Encodings">&quot;Unicode Encodings&quot; in perlunicode</a> has pictures of how this works.</p>

<p>Assuming you know you&#39;re dealing with a UTF-8 string, you can find out how long the first character in it is with the <code>UTF8SKIP</code> macro:</p>

<pre><code>char *utf = &quot;\305\233\340\240\201&quot;;
I32 len;

len = UTF8SKIP(utf); /* len is 2 here */
utf += len;
len = UTF8SKIP(utf); /* len is 3 here */</code></pre>

<p>Another way to skip over characters in a UTF-8 string is to use <code>utf8_hop</code>, which takes a string and a number of characters to skip over. You&#39;re on your own about bounds checking, though, so don&#39;t use it lightly.</p>

<p>All bytes in a multi-byte UTF-8 character will have the high bit set, so you can test if you need to do something special with this character like this (the <code>UTF8_IS_INVARIANT()</code> is a macro that tests whether the byte is encoded as a single byte even in UTF-8):</p>

<pre><code>U8 *utf;     /* Initialize this to point to the beginning of the
                sequence to convert */
U8 *utf_end; /* Initialize this to 1 beyond the end of the sequence
                pointed to by &#39;utf&#39; */
UV uv;	 /* Returned code point; note: a UV, not a U8, not a
                char */
STRLEN len; /* Returned length of character in bytes */

if (!UTF8_IS_INVARIANT(*utf))
    /* Must treat this as UTF-8 */
    uv = utf8_to_uvchr_buf(utf, utf_end, &amp;len);
else
    /* OK to treat this character as a byte */
    uv = *utf;</code></pre>

<p>You can also see in that example that we use <code>utf8_to_uvchr_buf</code> to get the value of the character; the inverse function <code>uvchr_to_utf8</code> is available for putting a UV into UTF-8:</p>

<pre><code>if (!UVCHR_IS_INVARIANT(uv))
    /* Must treat this as UTF8 */
    utf8 = uvchr_to_utf8(utf8, uv);
else
    /* OK to treat this character as a byte */
    *utf8++ = uv;</code></pre>

<p>You <b>must</b> convert characters to UVs using the above functions if you&#39;re ever in a situation where you have to match UTF-8 and non-UTF-8 characters. You may not skip over UTF-8 characters in this case. If you do this, you&#39;ll lose the ability to match hi-bit non-UTF-8 characters; for instance, if your UTF-8 string contains <code>v196.172</code>, and you skip that character, you can never match a <code>chr(200)</code> in a non-UTF-8 string. So don&#39;t do that!</p>

<p>(Note that we don&#39;t have to test for invariant characters in the examples above. The functions work on any well-formed UTF-8 input. It&#39;s just that its faster to avoid the function overhead when it&#39;s not needed.)</p>

<h2 id="How-does-Perl-store-UTF-8-strings?"><a class="permalink" href="perlguts.html#How-does-Perl-store-UTF-8-strings?">#</a><a id="How4"></a><a id="How-does-Perl-store-UTF-8-strings"></a>How does Perl store UTF-8 strings?</h2>

<p>Currently, Perl deals with UTF-8 strings and non-UTF-8 strings slightly differently. A flag in the SV, <code>SVf_UTF8</code>, indicates that the string is internally encoded as UTF-8. Without it, the byte value is the codepoint number and vice versa. This flag is only meaningful if the SV is <code>SvPOK</code> or immediately after stringification via <code>SvPV</code> or a similar macro. You can check and manipulate this flag with the following macros:</p>

<pre><code class="plaintext">SvUTF8(sv)
SvUTF8_on(sv)
SvUTF8_off(sv)</code></pre>

<p>This flag has an important effect on Perl&#39;s treatment of the string: if UTF-8 data is not properly distinguished, regular expressions, <code>length</code>, <code>substr</code> and other string handling operations will have undesirable (wrong) results.</p>

<p>The problem comes when you have, for instance, a string that isn&#39;t flagged as UTF-8, and contains a byte sequence that could be UTF-8 -- especially when combining non-UTF-8 and UTF-8 strings.</p>

<p>Never forget that the <code>SVf_UTF8</code> flag is separate from the PV value; you need to be sure you don&#39;t accidentally knock it off while you&#39;re manipulating SVs. More specifically, you cannot expect to do this:</p>

<pre><code>SV *sv;
SV *nsv;
STRLEN len;
char *p;

p = SvPV(sv, len);
frobnicate(p);
nsv = newSVpvn(p, len);</code></pre>

<p>The <code>char*</code> string does not tell you the whole story, and you can&#39;t copy or reconstruct an SV just by copying the string value. Check if the old SV has the UTF8 flag set (<i>after</i> the <code>SvPV</code> call), and act accordingly:</p>

<pre><code>p = SvPV(sv, len);
is_utf8 = SvUTF8(sv);
frobnicate(p, is_utf8);
nsv = newSVpvn(p, len);
if (is_utf8)
    SvUTF8_on(nsv);</code></pre>

<p>In the above, your <code>frobnicate</code> function has been changed to be made aware of whether or not it&#39;s dealing with UTF-8 data, so that it can handle the string appropriately.</p>

<p>Since just passing an SV to an XS function and copying the data of the SV is not enough to copy the UTF8 flags, even less right is just passing a <span style="white-space: nowrap;"><code>char *</code></span> to an XS function.</p>

<p>For full generality, use the <a href="perlapi.html#DO_UTF8"><code>DO_UTF8</code></a> macro to see if the string in an SV is to be <i>treated</i> as UTF-8. This takes into account if the call to the XS function is being made from within the scope of <a href="bytes.html"><span style="white-space: nowrap;"><code>use bytes</code></span></a>. If so, the underlying bytes that comprise the UTF-8 string are to be exposed, rather than the character they represent. But this pragma should only really be used for debugging and perhaps low-level testing at the byte level. Hence most XS code need not concern itself with this, but various areas of the perl core do need to support it.</p>

<p>And this isn&#39;t the whole story. Starting in Perl v5.12, strings that aren&#39;t encoded in UTF-8 may also be treated as Unicode under various conditions (see <a href="perlunicode.html#ASCII-Rules-versus-Unicode-Rules">&quot;ASCII Rules versus Unicode Rules&quot; in perlunicode</a>). This is only really a problem for characters whose ordinals are between 128 and 255, and their behavior varies under ASCII versus Unicode rules in ways that your code cares about (see <a href="perlunicode.html#The-%22Unicode-Bug%22">&quot;The &quot;Unicode Bug&quot;&quot; in perlunicode</a>). There is no published API for dealing with this, as it is subject to change, but you can look at the code for <code>pp_lc</code> in <i>pp.c</i> for an example as to how it&#39;s currently done.</p>

<h2 id="How-do-I-pass-a-Perl-string-to-a-C-library?"><a class="permalink" href="perlguts.html#How-do-I-pass-a-Perl-string-to-a-C-library?">#</a><a id="How5"></a><a id="How-do-I-pass-a-Perl-string-to-a-C-library"></a>How do I pass a Perl string to a C library?</h2>

<p>A Perl string, conceptually, is an opaque sequence of code points. Many C libraries expect their inputs to be &quot;classical&quot; C strings, which are arrays of octets 1-255, terminated with a NUL byte. Your job when writing an interface between Perl and a C library is to define the mapping between Perl and that library.</p>

<p>Generally speaking, <code>SvPVbyte</code> and related macros suit this task well. These assume that your Perl string is a &quot;byte string&quot;, i.e., is either raw, undecoded input into Perl or is pre-encoded to, e.g., UTF-8.</p>

<p>Alternatively, if your C library expects UTF-8 text, you can use <code>SvPVutf8</code> and related macros. This has the same effect as encoding to UTF-8 then calling the corresponding <code>SvPVbyte</code>-related macro.</p>

<p>Some C libraries may expect other encodings (e.g., UTF-16LE). To give Perl strings to such libraries you must either do that encoding in Perl then use <code>SvPVbyte</code>, or use an intermediary C library to convert from however Perl stores the string to the desired encoding.</p>

<p>Take care also that NULs in your Perl string don&#39;t confuse the C library. If possible, give the string&#39;s length to the C library; if that&#39;s not possible, consider rejecting strings that contain NUL bytes.</p>

<h3 id="What-about-SvPV,-SvPV_nolen,-etc.?"><a class="permalink" href="perlguts.html#What-about-SvPV,-SvPV_nolen,-etc.?">#</a><a id="What3"></a><a id="What-about-SvPV-SvPV_nolen-etc"></a>What about <code>SvPV</code>, <code>SvPV_nolen</code>, etc.?</h3>

<p>Consider a 3-character Perl string <code>$foo = &quot;\x64\x78\x8c&quot;</code>. Perl can store these 3 characters either of two ways:</p>

<ul>

<li><p>bytes: 0x64 0x78 0x8c</p>

</li>
<li><p>UTF-8: 0x64 0x78 0xc2 0x8c</p>

</li>
</ul>

<p>Now let&#39;s say you convert <code>$foo</code> to a C string thus:</p>

<pre><code>STRLEN strlen;
char *str = SvPV(foo_sv, strlen);</code></pre>

<p>At this point <code>str</code> could point to a 3-byte C string or a 4-byte one.</p>

<p>Generally speaking, we want <code>str</code> to be the same regardless of how Perl stores <code>$foo</code>, so the ambiguity here is undesirable. <code>SvPVbyte</code> and <code>SvPVutf8</code> solve that by giving predictable output: use <code>SvPVbyte</code> if your C library expects byte strings, or <code>SvPVutf8</code> if it expects UTF-8.</p>

<p>If your C library happens to support both encodings, then <code>SvPV</code>--always in tandem with lookups to <code>SvUTF8</code>!--may be safe and (slightly) more efficient.</p>

<p><b>TESTING</b> <b>TIP:</b> Use <a href="utf8.html">utf8</a>&#39;s <code>upgrade</code> and <code>downgrade</code> functions in your tests to ensure consistent handling regardless of Perl&#39;s internal encoding.</p>

<h2 id="How-do-I-convert-a-string-to-UTF-8?"><a class="permalink" href="perlguts.html#How-do-I-convert-a-string-to-UTF-8?">#</a><a id="How6"></a><a id="How-do-I-convert-a-string-to-UTF-8"></a>How do I convert a string to UTF-8?</h2>

<p>If you&#39;re mixing UTF-8 and non-UTF-8 strings, it is necessary to upgrade the non-UTF-8 strings to UTF-8. If you&#39;ve got an SV, the easiest way to do this is:</p>

<pre><code>sv_utf8_upgrade(sv);</code></pre>

<p>However, you must not do this, for example:</p>

<pre><code>if (!SvUTF8(left))
    sv_utf8_upgrade(left);</code></pre>

<p>If you do this in a binary operator, you will actually change one of the strings that came into the operator, and, while it shouldn&#39;t be noticeable by the end user, it can cause problems in deficient code.</p>

<p>Instead, <code>bytes_to_utf8</code> will give you a UTF-8-encoded <b>copy</b> of its string argument. This is useful for having the data available for comparisons and so on, without harming the original SV. There&#39;s also <code>utf8_to_bytes</code> to go the other way, but naturally, this will fail if the string contains any characters above 255 that can&#39;t be represented in a single byte.</p>

<h2 id="How-do-I-compare-strings?"><a class="permalink" href="perlguts.html#How-do-I-compare-strings?">#</a><a id="How7"></a><a id="How-do-I-compare-strings"></a>How do I compare strings?</h2>

<p><a href="perlapi.html#sv_cmp">&quot;sv_cmp&quot; in perlapi</a> and <a href="perlapi.html#sv_cmp_flags">&quot;sv_cmp_flags&quot; in perlapi</a> do a lexigraphic comparison of two SV&#39;s, and handle UTF-8ness properly. Note, however, that Unicode specifies a much fancier mechanism for collation, available via the <a href="./Unicode::Collate.html">Unicode::Collate</a> module.</p>

<p>To just compare two strings for equality/non-equality, you can just use <a href="perlapi.html#memEQ"><code>memEQ()</code></a> and <a href="perlapi.html#memEQ"><code>memNE()</code></a> as usual, except the strings must be both UTF-8 or not UTF-8 encoded.</p>

<p>To compare two strings case-insensitively, use <a href="perlapi.html#foldEQ_utf8"><code>foldEQ_utf8()</code></a> (the strings don&#39;t have to have the same UTF-8ness).</p>

<h2 id="Is-there-anything-else-I-need-to-know?"><a class="permalink" href="perlguts.html#Is-there-anything-else-I-need-to-know?">#</a><a id="Is"></a><a id="Is-there-anything-else-I-need-to-know"></a>Is there anything else I need to know?</h2>

<p>Not really. Just remember these things:</p>

<ul>

<li><p>There&#39;s no way to tell if a <span style="white-space: nowrap;"><code>char *</code></span> or <span style="white-space: nowrap;"><code>U8 *</code></span> string is UTF-8 or not. But you can tell if an SV is to be treated as UTF-8 by calling <code>DO_UTF8</code> on it, after stringifying it with <code>SvPV</code> or a similar macro. And, you can tell if SV is actually UTF-8 (even if it is not to be treated as such) by looking at its <code>SvUTF8</code> flag (again after stringifying it). Don&#39;t forget to set the flag if something should be UTF-8. Treat the flag as part of the PV, even though it&#39;s not -- if you pass on the PV to somewhere, pass on the flag too.</p>

</li>
<li><p>If a string is UTF-8, <b>always</b> use <code>utf8_to_uvchr_buf</code> to get at the value, unless <code>UTF8_IS_INVARIANT(*s)</code> in which case you can use <code>*s</code>.</p>

</li>
<li><p>When writing a character UV to a UTF-8 string, <b>always</b> use <code>uvchr_to_utf8</code>, unless <code>UVCHR_IS_INVARIANT(uv))</code> in which case you can use <code>*s = uv</code>.</p>

</li>
<li><p>Mixing UTF-8 and non-UTF-8 strings is tricky. Use <code>bytes_to_utf8</code> to get a new string which is UTF-8 encoded, and then combine them.</p>

</li>
</ul>

<h1 id="Custom-Operators"><a class="permalink" href="perlguts.html#Custom-Operators">#</a><a id="Custom"></a>Custom Operators</h1>

<p>Custom operator support is an experimental feature that allows you to define your own ops. This is primarily to allow the building of interpreters for other languages in the Perl core, but it also allows optimizations through the creation of &quot;macro-ops&quot; (ops which perform the functions of multiple ops which are usually executed together, such as <code>gvsv, gvsv, add</code>.)</p>

<p>This feature is implemented as a new op type, <code>OP_CUSTOM</code>. The Perl core does not &quot;know&quot; anything special about this op type, and so it will not be involved in any optimizations. This also means that you can define your custom ops to be any op structure -- unary, binary, list and so on -- you like.</p>

<p>It&#39;s important to know what custom operators won&#39;t do for you. They won&#39;t let you add new syntax to Perl, directly. They won&#39;t even let you add new keywords, directly. In fact, they won&#39;t change the way Perl compiles a program at all. You have to do those changes yourself, after Perl has compiled the program. You do this either by manipulating the op tree using a <code>CHECK</code> block and the <code>B::Generate</code> module, or by adding a custom peephole optimizer with the <code>optimize</code> module.</p>

<p>When you do this, you replace ordinary Perl ops with custom ops by creating ops with the type <code>OP_CUSTOM</code> and the <code>op_ppaddr</code> of your own PP function. This should be defined in XS code, and should look like the PP ops in <code>pp_*.c</code>. You are responsible for ensuring that your op takes the appropriate number of values from the stack, and you are responsible for adding stack marks if necessary.</p>

<p>You should also &quot;register&quot; your op with the Perl interpreter so that it can produce sensible error and warning messages. Since it is possible to have multiple custom ops within the one &quot;logical&quot; op type <code>OP_CUSTOM</code>, Perl uses the value of <code>o-&gt;op_ppaddr</code> to determine which custom op it is dealing with. You should create an <code>XOP</code> structure for each ppaddr you use, set the properties of the custom op with <code>XopENTRY_set</code>, and register the structure against the ppaddr using <code>Perl_custom_op_register</code>. A trivial example might look like:</p>

<pre><code>static XOP my_xop;
static OP *my_pp(pTHX);

BOOT:
    XopENTRY_set(&amp;my_xop, xop_name, &quot;myxop&quot;);
    XopENTRY_set(&amp;my_xop, xop_desc, &quot;Useless custom op&quot;);
    Perl_custom_op_register(aTHX_ my_pp, &amp;my_xop);</code></pre>

<p>The available fields in the structure are:</p>

<dl>

<dt id="xop_name"><a class="permalink" href="perlguts.html#xop_name">#</a>xop_name</dt>
<dd>

<p>A short name for your op. This will be included in some error messages, and will also be returned as <code>$op-&gt;name</code> by the <a href="B.html">B</a> module, so it will appear in the output of module like <a href="./B::Concise.html">B::Concise</a>.</p>

</dd>
<dt id="xop_desc"><a class="permalink" href="perlguts.html#xop_desc">#</a>xop_desc</dt>
<dd>

<p>A short description of the function of the op.</p>

</dd>
<dt id="xop_class"><a class="permalink" href="perlguts.html#xop_class">#</a>xop_class</dt>
<dd>

<p>Which of the various <code>*OP</code> structures this op uses. This should be one of the <code>OA_*</code> constants from <i>op.h</i>, namely</p>

<dl>

<dt id="OA_BASEOP"><a class="permalink" href="perlguts.html#OA_BASEOP">#</a>OA_BASEOP</dt>
<dd>

</dd>
<dt id="OA_UNOP"><a class="permalink" href="perlguts.html#OA_UNOP">#</a>OA_UNOP</dt>
<dd>

</dd>
<dt id="OA_BINOP"><a class="permalink" href="perlguts.html#OA_BINOP">#</a>OA_BINOP</dt>
<dd>

</dd>
<dt id="OA_LOGOP"><a class="permalink" href="perlguts.html#OA_LOGOP">#</a>OA_LOGOP</dt>
<dd>

</dd>
<dt id="OA_LISTOP"><a class="permalink" href="perlguts.html#OA_LISTOP">#</a>OA_LISTOP</dt>
<dd>

</dd>
<dt id="OA_PMOP"><a class="permalink" href="perlguts.html#OA_PMOP">#</a>OA_PMOP</dt>
<dd>

</dd>
<dt id="OA_SVOP"><a class="permalink" href="perlguts.html#OA_SVOP">#</a>OA_SVOP</dt>
<dd>

</dd>
<dt id="OA_PADOP"><a class="permalink" href="perlguts.html#OA_PADOP">#</a>OA_PADOP</dt>
<dd>

</dd>
<dt id="OA_PVOP_OR_SVOP"><a class="permalink" href="perlguts.html#OA_PVOP_OR_SVOP">#</a>OA_PVOP_OR_SVOP</dt>
<dd>

<p>This should be interpreted as &#39;<code>PVOP</code>&#39; only. The <code>_OR_SVOP</code> is because the only core <code>PVOP</code>, <code>OP_TRANS</code>, can sometimes be a <code>SVOP</code> instead.</p>

</dd>
<dt id="OA_LOOP"><a class="permalink" href="perlguts.html#OA_LOOP">#</a>OA_LOOP</dt>
<dd>

</dd>
<dt id="OA_COP"><a class="permalink" href="perlguts.html#OA_COP">#</a>OA_COP</dt>
<dd>

</dd>
</dl>

<p>The other <code>OA_*</code> constants should not be used.</p>

</dd>
<dt id="xop_peep"><a class="permalink" href="perlguts.html#xop_peep">#</a>xop_peep</dt>
<dd>

<p>This member is of type <code>Perl_cpeep_t</code>, which expands to <code>void (*Perl_cpeep_t)(aTHX_ OP *o, OP *oldop)</code>. If it is set, this function will be called from <code>Perl_rpeep</code> when ops of this type are encountered by the peephole optimizer. <i>o</i> is the OP that needs optimizing; <i>oldop</i> is the previous OP optimized, whose <code>op_next</code> points to <i>o</i>.</p>

</dd>
</dl>

<p><code>B::Generate</code> directly supports the creation of custom ops by name.</p>

<h1 id="Stacks"><a class="permalink" href="perlguts.html#Stacks">#</a>Stacks</h1>

<p>Descriptions above occasionally refer to &quot;the stack&quot;, but there are in fact many stack-like data structures within the perl interpreter. When otherwise unqualified, &quot;the stack&quot; usually refers to the value stack.</p>

<p>The various stacks have different purposes, and operate in slightly different ways. Their differences are noted below.</p>

<h2 id="Value-Stack"><a class="permalink" href="perlguts.html#Value-Stack">#</a><a id="Value"></a>Value Stack</h2>

<p>This stack stores the values that regular perl code is operating on, usually intermediate values of expressions within a statement. The stack itself is formed of an array of SV pointers.</p>

<p>The base of this stack is pointed to by the interpreter variable <code>PL_stack_base</code>, of type <code>SV **</code>.</p>

<p>The head of the stack is <code>PL_stack_sp</code>, and points to the most recently-pushed item.</p>

<p>Items are pushed to the stack by using the <code>PUSHs()</code> macro or its variants described above; <code>XPUSHs()</code>, <code>mPUSHs()</code>, <code>mXPUSHs()</code> and the typed versions. Note carefully that the non-<code>X</code> versions of these macros do not check the size of the stack and assume it to be big enough. These must be paired with a suitable check of the stack&#39;s size, such as the <code>EXTEND</code> macro to ensure it is large enough. For example</p>

<pre><code>EXTEND(SP, 4);
mPUSHi(10);
mPUSHi(20);
mPUSHi(30);
mPUSHi(40);</code></pre>

<p>This is slightly more performant than making four separate checks in four separate <code>mXPUSHi()</code> calls.</p>

<p>As a further performance optimisation, the various <code>PUSH</code> macros all operate using a local variable <code>SP</code>, rather than the interpreter-global variable <code>PL_stack_sp</code>. This variable is declared by the <code>dSP</code> macro - though it is normally implied by XSUBs and similar so it is rare you have to consider it directly. Once declared, the <code>PUSH</code> macros will operate only on this local variable, so before invoking any other perl core functions you must use the <code>PUTBACK</code> macro to return the value from the local <code>SP</code> variable back to the interpreter variable. Similarly, after calling a perl core function which may have had reason to move the stack or push/pop values to it, you must use the <code>SPAGAIN</code> macro which refreshes the local <code>SP</code> value back from the interpreter one.</p>

<p>Items are popped from the stack by using the <code>POPs</code> macro or its typed versions, There is also a macro <code>TOPs</code> that inspects the topmost item without removing it.</p>

<p>Note specifically that SV pointers on the value stack do not contribute to the overall reference count of the xVs being referred to. If newly-created xVs are being pushed to the stack you must arrange for them to be destroyed at a suitable time; usually by using one of the <code>mPUSH*</code> macros or <code>sv_2mortal()</code> to mortalise the xV.</p>

<h2 id="Mark-Stack"><a class="permalink" href="perlguts.html#Mark-Stack">#</a><a id="Mark"></a>Mark Stack</h2>

<p>The value stack stores individual perl scalar values as temporaries between expressions. Some perl expressions operate on entire lists; for that purpose we need to know where on the stack each list begins. This is the purpose of the mark stack.</p>

<p>The mark stack stores integers as I32 values, which are the height of the value stack at the time before the list began; thus the mark itself actually points to the value stack entry one before the list. The list itself starts at <code>mark + 1</code>.</p>

<p>The base of this stack is pointed to by the interpreter variable <code>PL_markstack</code>, of type <code>I32 *</code>.</p>

<p>The head of the stack is <code>PL_markstack_ptr</code>, and points to the most recently-pushed item.</p>

<p>Items are pushed to the stack by using the <code>PUSHMARK()</code> macro. Even though the stack itself stores (value) stack indices as integers, the <code>PUSHMARK</code> macro should be given a stack pointer directly; it will calculate the index offset by comparing to the <code>PL_stack_sp</code> variable. Thus almost always the code to perform this is</p>

<pre><code>PUSHMARK(SP);</code></pre>

<p>Items are popped from the stack by the <code>POPMARK</code> macro. There is also a macro <code>TOPMARK</code> that inspects the topmost item without removing it. These macros return I32 index values directly. There is also the <code>dMARK</code> macro which declares a new SV double-pointer variable, called <code>mark</code>, which points at the marked stack slot; this is the usual macro that C code will use when operating on lists given on the stack.</p>

<p>As noted above, the <code>mark</code> variable itself will point at the most recently pushed value on the value stack before the list begins, and so the list itself starts at <code>mark + 1</code>. The values of the list may be iterated by code such as</p>

<pre><code>for(SV **svp = mark + 1; svp &lt;= PL_stack_sp; svp++) {
  SV *item = *svp;
  ...
}</code></pre>

<p>Note specifically in the case that the list is already empty, <code>mark</code> will equal <code>PL_stack_sp</code>.</p>

<p>Because the <code>mark</code> variable is converted to a pointer on the value stack, extra care must be taken if <code>EXTEND</code> or any of the <code>XPUSH</code> macros are invoked within the function, because the stack may need to be moved to extend it and so the existing pointer will now be invalid. If this may be a problem, a possible solution is to track the mark offset as an integer and track the mark itself later on after the stack had been moved.</p>

<pre><code>I32 markoff = POPMARK;

...

SP **mark = PL_stack_base + markoff;</code></pre>

<h2 id="Temporaries-Stack"><a class="permalink" href="perlguts.html#Temporaries-Stack">#</a><a id="Temporaries"></a>Temporaries Stack</h2>

<p>As noted above, xV references on the main value stack do not contribute to the reference count of an xV, and so another mechanism is used to track when temporary values which live on the stack must be released. This is the job of the temporaries stack.</p>

<p>The temporaries stack stores pointers to xVs whose reference counts will be decremented soon.</p>

<p>The base of this stack is pointed to by the interpreter variable <code>PL_tmps_stack</code>, of type <code>SV **</code>.</p>

<p>The head of the stack is indexed by <code>PL_tmps_ix</code>, an integer which stores the index in the array of the most recently-pushed item.</p>

<p>There is no public API to directly push items to the temporaries stack. Instead, the API function <code>sv_2mortal()</code> is used to mortalize an xV, adding its address to the temporaries stack.</p>

<p>Likewise, there is no public API to read values from the temporaries stack. Instead, the macros <code>SAVETMPS</code> and <code>FREETMPS</code> are used. The <code>SAVETMPS</code> macro establishes the base levels of the temporaries stack, by capturing the current value of <code>PL_tmps_ix</code> into <code>PL_tmps_floor</code> and saving the previous value to the save stack. Thereafter, whenever <code>FREETMPS</code> is invoked all of the temporaries that have been pushed since that level are reclaimed.</p>

<p>While it is common to see these two macros in pairs within an <code>ENTER</code>/ <code>LEAVE</code> pair, it is not necessary to match them. It is permitted to invoke <code>FREETMPS</code> multiple times since the most recent <code>SAVETMPS</code>; for example in a loop iterating over elements of a list. While you can invoke <code>SAVETMPS</code> multiple times within a scope pair, it is unlikely to be useful. Subsequent invocations will move the temporaries floor further up, thus effectively trapping the existing temporaries to only be released at the end of the scope.</p>

<h2 id="Save-Stack"><a class="permalink" href="perlguts.html#Save-Stack">#</a><a id="Save"></a>Save Stack</h2>

<p>The save stack is used by perl to implement the <code>local</code> keyword and other similar behaviours; any cleanup operations that need to be performed when leaving the current scope. Items pushed to this stack generally capture the current value of some internal variable or state, which will be restored when the scope is unwound due to leaving, <code>return</code>, <code>die</code>, <code>goto</code> or other reasons.</p>

<p>Whereas other perl internal stacks store individual items all of the same type (usually SV pointers or integers), the items pushed to the save stack are formed of many different types, having multiple fields to them. For example, the <code>SAVEt_INT</code> type needs to store both the address of the <code>int</code> variable to restore, and the value to restore it to. This information could have been stored using fields of a <code>struct</code>, but would have to be large enough to store three pointers in the largest case, which would waste a lot of space in most of the smaller cases.</p>

<p>Instead, the stack stores information in a variable-length encoding of <code>ANY</code> structures. The final value pushed is stored in the <code>UV</code> field which encodes the kind of item held by the preceeding items; the count and types of which will depend on what kind of item is being stored. The kind field is pushed last because that will be the first field to be popped when unwinding items from the stack.</p>

<p>The base of this stack is pointed to by the interpreter variable <code>PL_savestack</code>, of type <code>ANY *</code>.</p>

<p>The head of the stack is indexed by <code>PL_savestack_ix</code>, an integer which stores the index in the array at which the next item should be pushed. (Note that this is different to most other stacks, which reference the most recently-pushed item).</p>

<p>Items are pushed to the save stack by using the various <code>SAVE...()</code> macros. Many of these macros take a variable and store both its address and current value on the save stack, ensuring that value gets restored on scope exit.</p>

<pre><code class="plaintext">SAVEI8(i8)
SAVEI16(i16)
SAVEI32(i32)
SAVEINT(i)
...</code></pre>

<p>There are also a variety of other special-purpose macros which save particular types or values of interest. <code>SAVETMPS</code> has already been mentioned above. Others include <code>SAVEFREEPV</code> which arranges for a PV (i.e. a string buffer) to be freed, or <code>SAVEDESTRUCTOR</code> which arranges for a given function pointer to be invoked on scope exit. A full list of such macros can be found in <i>scope.h</i>.</p>

<p>There is no public API for popping individual values or items from the save stack. Instead, via the scope stack, the <code>ENTER</code> and <code>LEAVE</code> pair form a way to start and stop nested scopes. Leaving a nested scope via <code>LEAVE</code> will restore all of the saved values that had been pushed since the most recent <code>ENTER</code>.</p>

<h2 id="Scope-Stack"><a class="permalink" href="perlguts.html#Scope-Stack">#</a><a id="Scope"></a>Scope Stack</h2>

<p>As with the mark stack to the value stack, the scope stack forms a pair with the save stack. The scope stack stores the height of the save stack at which nested scopes begin, and allows the save stack to be unwound back to that point when the scope is left.</p>

<p>When perl is built with debugging enabled, there is a second part to this stack storing human-readable string names describing the type of stack context. Each push operation saves the name as well as the height of the save stack, and each pop operation checks the topmost name with what is expected, causing an assertion failure if the name does not match.</p>

<p>The base of this stack is pointed to by the interpreter variable <code>PL_scopestack</code>, of type <code>I32 *</code>. If enabled, the scope stack names are stored in a separate array pointed to by <code>PL_scopestack_name</code>, of type <code>const char **</code>.</p>

<p>The head of the stack is indexed by <code>PL_scopestack_ix</code>, an integer which stores the index of the array or arrays at which the next item should be pushed. (Note that this is different to most other stacks, which reference the most recently-pushed item).</p>

<p>Values are pushed to the scope stack using the <code>ENTER</code> macro, which begins a new nested scope. Any items pushed to the save stack are then restored at the next nested invocation of the <code>LEAVE</code> macro.</p>

<h1 id="Dynamic-Scope-and-the-Context-Stack"><a class="permalink" href="perlguts.html#Dynamic-Scope-and-the-Context-Stack">#</a><a id="Dynamic"></a>Dynamic Scope and the Context Stack</h1>

<p><b>Note:</b> this section describes a non-public internal API that is subject to change without notice.</p>

<h2 id="Introduction-to-the-context-stack"><a class="permalink" href="perlguts.html#Introduction-to-the-context-stack">#</a><a id="Introduction"></a>Introduction to the context stack</h2>

<p>In Perl, dynamic scoping refers to the runtime nesting of things like subroutine calls, evals etc, as well as the entering and exiting of block scopes. For example, the restoring of a <code>local</code>ised variable is determined by the dynamic scope.</p>

<p>Perl tracks the dynamic scope by a data structure called the context stack, which is an array of <code>PERL_CONTEXT</code> structures, and which is itself a big union for all the types of context. Whenever a new scope is entered (such as a block, a <code>for</code> loop, or a subroutine call), a new context entry is pushed onto the stack. Similarly when leaving a block or returning from a subroutine call etc. a context is popped. Since the context stack represents the current dynamic scope, it can be searched. For example, <code>next LABEL</code> searches back through the stack looking for a loop context that matches the label; <code>return</code> pops contexts until it finds a sub or eval context or similar; <code>caller</code> examines sub contexts on the stack.</p>

<p>Each context entry is labelled with a context type, <code>cx_type</code>. Typical context types are <code>CXt_SUB</code>, <code>CXt_EVAL</code> etc., as well as <code>CXt_BLOCK</code> and <code>CXt_NULL</code> which represent a basic scope (as pushed by <code>pp_enter</code>) and a sort block. The type determines which part of the context union are valid.</p>

<p>The main division in the context struct is between a substitution scope (<code>CXt_SUBST</code>) and block scopes, which are everything else. The former is just used while executing <code>s///e</code>, and won&#39;t be discussed further here.</p>

<p>All the block scope types share a common base, which corresponds to <code>CXt_BLOCK</code>. This stores the old values of various scope-related variables like <code>PL_curpm</code>, as well as information about the current scope, such as <code>gimme</code>. On scope exit, the old variables are restored.</p>

<p>Particular block scope types store extra per-type information. For example, <code>CXt_SUB</code> stores the currently executing CV, while the various for loop types might hold the original loop variable SV. On scope exit, the per-type data is processed; for example the CV has its reference count decremented, and the original loop variable is restored.</p>

<p>The macro <code>cxstack</code> returns the base of the current context stack, while <code>cxstack_ix</code> is the index of the current frame within that stack.</p>

<p>In fact, the context stack is actually part of a stack-of-stacks system; whenever something unusual is done such as calling a <code>DESTROY</code> or tie handler, a new stack is pushed, then popped at the end.</p>

<p>Note that the API described here changed considerably in perl 5.24; prior to that, big macros like <code>PUSHBLOCK</code> and <code>POPSUB</code> were used; in 5.24 they were replaced by the inline static functions described below. In addition, the ordering and detail of how these macros/function work changed in many ways, often subtly. In particular they didn&#39;t handle saving the savestack and temps stack positions, and required additional <code>ENTER</code>, <code>SAVETMPS</code> and <code>LEAVE</code> compared to the new functions. The old-style macros will not be described further.</p>

<h2 id="Pushing-contexts"><a class="permalink" href="perlguts.html#Pushing-contexts">#</a><a id="Pushing"></a>Pushing contexts</h2>

<p>For pushing a new context, the two basic functions are <code>cx = cx_pushblock()</code>, which pushes a new basic context block and returns its address, and a family of similar functions with names like <code>cx_pushsub(cx)</code> which populate the additional type-dependent fields in the <code>cx</code> struct. Note that <code>CXt_NULL</code> and <code>CXt_BLOCK</code> don&#39;t have their own push functions, as they don&#39;t store any data beyond that pushed by <code>cx_pushblock</code>.</p>

<p>The fields of the context struct and the arguments to the <code>cx_*</code> functions are subject to change between perl releases, representing whatever is convenient or efficient for that release.</p>

<p>A typical context stack pushing can be found in <code>pp_entersub</code>; the following shows a simplified and stripped-down example of a non-XS call, along with comments showing roughly what each function does.</p>

<pre><code>dMARK;
U8 gimme      = GIMME_V;
bool hasargs  = cBOOL(PL_op-&gt;op_flags &amp; OPf_STACKED);
OP *retop     = PL_op-&gt;op_next;
I32 old_ss_ix = PL_savestack_ix;
CV *cv        = ....;

/* ... make mortal copies of stack args which are PADTMPs here ... */

/* ... do any additional savestack pushes here ... */

/* Now push a new context entry of type &#39;CXt_SUB&#39;; initially just
 * doing the actions common to all block types: */

cx = cx_pushblock(CXt_SUB, gimme, MARK, old_ss_ix);

    /* this does (approximately):
        CXINC;              /* cxstack_ix++ (grow if necessary) */
        cx = CX_CUR();      /* and get the address of new frame */
        cx-&gt;cx_type        = CXt_SUB;
        cx-&gt;blk_gimme      = gimme;
        cx-&gt;blk_oldsp      = MARK - PL_stack_base;
        cx-&gt;blk_oldsaveix  = old_ss_ix;
        cx-&gt;blk_oldcop     = PL_curcop;
        cx-&gt;blk_oldmarksp  = PL_markstack_ptr - PL_markstack;
        cx-&gt;blk_oldscopesp = PL_scopestack_ix;
        cx-&gt;blk_oldpm      = PL_curpm;
        cx-&gt;blk_old_tmpsfloor = PL_tmps_floor;

        PL_tmps_floor        = PL_tmps_ix;
    */


/* then update the new context frame with subroutine-specific info,
 * such as the CV about to be executed: */

cx_pushsub(cx, cv, retop, hasargs);

    /* this does (approximately):
        cx-&gt;blk_sub.cv          = cv;
        cx-&gt;blk_sub.olddepth    = CvDEPTH(cv);
        cx-&gt;blk_sub.prevcomppad = PL_comppad;
        cx-&gt;cx_type            |= (hasargs) ? CXp_HASARGS : 0;
        cx-&gt;blk_sub.retop       = retop;
        SvREFCNT_inc_simple_void_NN(cv);
    */</code></pre>

<p>Note that <code>cx_pushblock()</code> sets two new floors: for the args stack (to <code>MARK</code>) and the temps stack (to <code>PL_tmps_ix</code>). While executing at this scope level, every <code>nextstate</code> (amongst others) will reset the args and tmps stack levels to these floors. Note that since <code>cx_pushblock</code> uses the current value of <code>PL_tmps_ix</code> rather than it being passed as an arg, this dictates at what point <code>cx_pushblock</code> should be called. In particular, any new mortals which should be freed only on scope exit (rather than at the next <code>nextstate</code>) should be created first.</p>

<p>Most callers of <code>cx_pushblock</code> simply set the new args stack floor to the top of the previous stack frame, but for <code>CXt_LOOP_LIST</code> it stores the items being iterated over on the stack, and so sets <code>blk_oldsp</code> to the top of these items instead. Note that, contrary to its name, <code>blk_oldsp</code> doesn&#39;t always represent the value to restore <code>PL_stack_sp</code> to on scope exit.</p>

<p>Note the early capture of <code>PL_savestack_ix</code> to <code>old_ss_ix</code>, which is later passed as an arg to <code>cx_pushblock</code>. In the case of <code>pp_entersub</code>, this is because, although most values needing saving are stored in fields of the context struct, an extra value needs saving only when the debugger is running, and it doesn&#39;t make sense to bloat the struct for this rare case. So instead it is saved on the savestack. Since this value gets calculated and saved before the context is pushed, it is necessary to pass the old value of <code>PL_savestack_ix</code> to <code>cx_pushblock</code>, to ensure that the saved value gets freed during scope exit. For most users of <code>cx_pushblock</code>, where nothing needs pushing on the save stack, <code>PL_savestack_ix</code> is just passed directly as an arg to <code>cx_pushblock</code>.</p>

<p>Note that where possible, values should be saved in the context struct rather than on the save stack; it&#39;s much faster that way.</p>

<p>Normally <code>cx_pushblock</code> should be immediately followed by the appropriate <code>cx_pushfoo</code>, with nothing between them; this is because if code in-between could die (e.g. a warning upgraded to fatal), then the context stack unwinding code in <code>dounwind</code> would see (in the example above) a <code>CXt_SUB</code> context frame, but without all the subroutine-specific fields set, and crashes would soon ensue.</p>

<p>Where the two must be separate, initially set the type to <code>CXt_NULL</code> or <code>CXt_BLOCK</code>, and later change it to <code>CXt_foo</code> when doing the <code>cx_pushfoo</code>. This is exactly what <code>pp_enteriter</code> does, once it&#39;s determined which type of loop it&#39;s pushing.</p>

<h2 id="Popping-contexts"><a class="permalink" href="perlguts.html#Popping-contexts">#</a><a id="Popping"></a>Popping contexts</h2>

<p>Contexts are popped using <code>cx_popsub()</code> etc. and <code>cx_popblock()</code>. Note however, that unlike <code>cx_pushblock</code>, neither of these functions actually decrement the current context stack index; this is done separately using <code>CX_POP()</code>.</p>

<p>There are two main ways that contexts are popped. During normal execution as scopes are exited, functions like <code>pp_leave</code>, <code>pp_leaveloop</code> and <code>pp_leavesub</code> process and pop just one context using <code>cx_popfoo</code> and <code>cx_popblock</code>. On the other hand, things like <code>pp_return</code> and <code>next</code> may have to pop back several scopes until a sub or loop context is found, and exceptions (such as <code>die</code>) need to pop back contexts until an eval context is found. Both of these are accomplished by <code>dounwind()</code>, which is capable of processing and popping all contexts above the target one.</p>

<p>Here is a typical example of context popping, as found in <code>pp_leavesub</code> (simplified slightly):</p>

<pre><code>U8 gimme;
PERL_CONTEXT *cx;
SV **oldsp;
OP *retop;

cx = CX_CUR();

gimme = cx-&gt;blk_gimme;
oldsp = PL_stack_base + cx-&gt;blk_oldsp; /* last arg of previous frame */

if (gimme == G_VOID)
    PL_stack_sp = oldsp;
else
    leave_adjust_stacks(oldsp, oldsp, gimme, 0);

CX_LEAVE_SCOPE(cx);
cx_popsub(cx);
cx_popblock(cx);
retop = cx-&gt;blk_sub.retop;
CX_POP(cx);

return retop;</code></pre>

<p>The steps above are in a very specific order, designed to be the reverse order of when the context was pushed. The first thing to do is to copy and/or protect any return arguments and free any temps in the current scope. Scope exits like an rvalue sub normally return a mortal copy of their return args (as opposed to lvalue subs). It is important to make this copy before the save stack is popped or variables are restored, or bad things like the following can happen:</p>

<pre><code>sub f { my $x =...; $x }  # $x freed before we get to copy it
sub f { /(...)/;    $1 }  # PL_curpm restored before $1 copied</code></pre>

<p>Although we wish to free any temps at the same time, we have to be careful not to free any temps which are keeping return args alive; nor to free the temps we have just created while mortal copying return args. Fortunately, <code>leave_adjust_stacks()</code> is capable of making mortal copies of return args, shifting args down the stack, and only processing those entries on the temps stack that are safe to do so.</p>

<p>In void context no args are returned, so it&#39;s more efficient to skip calling <code>leave_adjust_stacks()</code>. Also in void context, a <code>nextstate</code> op is likely to be imminently called which will do a <code>FREETMPS</code>, so there&#39;s no need to do that either.</p>

<p>The next step is to pop savestack entries: <code>CX_LEAVE_SCOPE(cx)</code> is just defined as <code>LEAVE_SCOPE(cx-&gt;blk_oldsaveix)</code>. Note that during the popping, it&#39;s possible for perl to call destructors, call <code>STORE</code> to undo localisations of tied vars, and so on. Any of these can die or call <code>exit()</code>. In this case, <code>dounwind()</code> will be called, and the current context stack frame will be re-processed. Thus it is vital that all steps in popping a context are done in such a way to support reentrancy. The other alternative, of decrementing <code>cxstack_ix</code> <i>before</i> processing the frame, would lead to leaks and the like if something died halfway through, or overwriting of the current frame.</p>

<p><code>CX_LEAVE_SCOPE</code> itself is safely re-entrant: if only half the savestack items have been popped before dying and getting trapped by eval, then the <code>CX_LEAVE_SCOPE</code>s in <code>dounwind</code> or <code>pp_leaveeval</code> will continue where the first one left off.</p>

<p>The next step is the type-specific context processing; in this case <code>cx_popsub</code>. In part, this looks like:</p>

<pre><code>cv = cx-&gt;blk_sub.cv;
CvDEPTH(cv) = cx-&gt;blk_sub.olddepth;
cx-&gt;blk_sub.cv = NULL;
SvREFCNT_dec(cv);</code></pre>

<p>where its processing the just-executed CV. Note that before it decrements the CV&#39;s reference count, it nulls the <code>blk_sub.cv</code>. This means that if it re-enters, the CV won&#39;t be freed twice. It also means that you can&#39;t rely on such type-specific fields having useful values after the return from <code>cx_popfoo</code>.</p>

<p>Next, <code>cx_popblock</code> restores all the various interpreter vars to their previous values or previous high water marks; it expands to:</p>

<pre><code>PL_markstack_ptr = PL_markstack + cx-&gt;blk_oldmarksp;
PL_scopestack_ix = cx-&gt;blk_oldscopesp;
PL_curpm         = cx-&gt;blk_oldpm;
PL_curcop        = cx-&gt;blk_oldcop;
PL_tmps_floor    = cx-&gt;blk_old_tmpsfloor;</code></pre>

<p>Note that it <i>doesn&#39;t</i> restore <code>PL_stack_sp</code>; as mentioned earlier, which value to restore it to depends on the context type (specifically <code>for (list) {}</code>), and what args (if any) it returns; and that will already have been sorted out earlier by <code>leave_adjust_stacks()</code>.</p>

<p>Finally, the context stack pointer is actually decremented by <code>CX_POP(cx)</code>. After this point, it&#39;s possible that that the current context frame could be overwritten by other contexts being pushed. Although things like ties and <code>DESTROY</code> are supposed to work within a new context stack, it&#39;s best not to assume this. Indeed on debugging builds, <code>CX_POP(cx)</code> deliberately sets <code>cx</code> to null to detect code that is still relying on the field values in that context frame. Note in the <code>pp_leavesub()</code> example above, we grab <code>blk_sub.retop</code> <i>before</i> calling <code>CX_POP</code>.</p>

<h2 id="Redoing-contexts"><a class="permalink" href="perlguts.html#Redoing-contexts">#</a><a id="Redoing"></a>Redoing contexts</h2>

<p>Finally, there is <code>cx_topblock(cx)</code>, which acts like a super-<code>nextstate</code> as regards to resetting various vars to their base values. It is used in places like <code>pp_next</code>, <code>pp_redo</code> and <code>pp_goto</code> where rather than exiting a scope, we want to re-initialise the scope. As well as resetting <code>PL_stack_sp</code> like <code>nextstate</code>, it also resets <code>PL_markstack_ptr</code>, <code>PL_scopestack_ix</code> and <code>PL_curpm</code>. Note that it doesn&#39;t do a <code>FREETMPS</code>.</p>

<h1 id="Slab-based-operator-allocation"><a class="permalink" href="perlguts.html#Slab-based-operator-allocation">#</a><a id="Slab"></a>Slab-based operator allocation</h1>

<p><b>Note:</b> this section describes a non-public internal API that is subject to change without notice.</p>

<p>Perl&#39;s internal error-handling mechanisms implement <code>die</code> (and its internal equivalents) using longjmp. If this occurs during lexing, parsing or compilation, we must ensure that any ops allocated as part of the compilation process are freed. (Older Perl versions did not adequately handle this situation: when failing a parse, they would leak ops that were stored in C <code>auto</code> variables and not linked anywhere else.)</p>

<p>To handle this situation, Perl uses <i>op slabs</i> that are attached to the currently-compiling CV. A slab is a chunk of allocated memory. New ops are allocated as regions of the slab. If the slab fills up, a new one is created (and linked from the previous one). When an error occurs and the CV is freed, any ops remaining are freed.</p>

<p>Each op is preceded by two pointers: one points to the next op in the slab, and the other points to the slab that owns it. The next-op pointer is needed so that Perl can iterate over a slab and free all its ops. (Op structures are of different sizes, so the slab&#39;s ops can&#39;t merely be treated as a dense array.) The slab pointer is needed for accessing a reference count on the slab: when the last op on a slab is freed, the slab itself is freed.</p>

<p>The slab allocator puts the ops at the end of the slab first. This will tend to allocate the leaves of the op tree first, and the layout will therefore hopefully be cache-friendly. In addition, this means that there&#39;s no need to store the size of the slab (see below on why slabs vary in size), because Perl can follow pointers to find the last op.</p>

<p>It might seem possible to eliminate slab reference counts altogether, by having all ops implicitly attached to <code>PL_compcv</code> when allocated and freed when the CV is freed. That would also allow <code>op_free</code> to skip <code>FreeOp</code> altogether, and thus free ops faster. But that doesn&#39;t work in those cases where ops need to survive beyond their CVs, such as re-evals.</p>

<p>The CV also has to have a reference count on the slab. Sometimes the first op created is immediately freed. If the reference count of the slab reaches 0, then it will be freed with the CV still pointing to it.</p>

<p>CVs use the <code>CVf_SLABBED</code> flag to indicate that the CV has a reference count on the slab. When this flag is set, the slab is accessible via <code>CvSTART</code> when <code>CvROOT</code> is not set, or by subtracting two pointers <code>(2*sizeof(I32 *))</code> from <code>CvROOT</code> when it is set. The alternative to this approach of sneaking the slab into <code>CvSTART</code> during compilation would be to enlarge the <code>xpvcv</code> struct by another pointer. But that would make all CVs larger, even though slab-based op freeing is typically of benefit only for programs that make significant use of string eval.</p>

<p>When the <code>CVf_SLABBED</code> flag is set, the CV takes responsibility for freeing the slab. If <code>CvROOT</code> is not set when the CV is freed or undeffed, it is assumed that a compilation error has occurred, so the op slab is traversed and all the ops are freed.</p>

<p>Under normal circumstances, the CV forgets about its slab (decrementing the reference count) when the root is attached. So the slab reference counting that happens when ops are freed takes care of freeing the slab. In some cases, the CV is told to forget about the slab (<code>cv_forget_slab</code>) precisely so that the ops can survive after the CV is done away with.</p>

<p>Forgetting the slab when the root is attached is not strictly necessary, but avoids potential problems with <code>CvROOT</code> being written over. There is code all over the place, both in core and on CPAN, that does things with <code>CvROOT</code>, so forgetting the slab makes things more robust and avoids potential problems.</p>

<p>Since the CV takes ownership of its slab when flagged, that flag is never copied when a CV is cloned, as one CV could free a slab that another CV still points to, since forced freeing of ops ignores the reference count (but asserts that it looks right).</p>

<p>To avoid slab fragmentation, freed ops are marked as freed and attached to the slab&#39;s freed chain (an idea stolen from DBM::Deep). Those freed ops are reused when possible. Not reusing freed ops would be simpler, but it would result in significantly higher memory usage for programs with large <code>if (DEBUG) {...}</code> blocks.</p>

<p><code>SAVEFREEOP</code> is slightly problematic under this scheme. Sometimes it can cause an op to be freed after its CV. If the CV has forcibly freed the ops on its slab and the slab itself, then we will be fiddling with a freed slab. Making <code>SAVEFREEOP</code> a no-op doesn&#39;t help, as sometimes an op can be savefreed when there is no compilation error, so the op would never be freed. It holds a reference count on the slab, so the whole slab would leak. So <code>SAVEFREEOP</code> now sets a special flag on the op (<code>-&gt;op_savefree</code>). The forced freeing of ops after a compilation error won&#39;t free any ops thus marked.</p>

<p>Since many pieces of code create tiny subroutines consisting of only a few ops, and since a huge slab would be quite a bit of baggage for those to carry around, the first slab is always very small. To avoid allocating too many slabs for a single CV, each subsequent slab is twice the size of the previous.</p>

<p>Smartmatch expects to be able to allocate an op at run time, run it, and then throw it away. For that to work the op is simply malloced when PL_compcv hasn&#39;t been set up. So all slab-allocated ops are marked as such (<code>-&gt;op_slabbed</code>), to distinguish them from malloced ops.</p>

<h1 id="AUTHORS"><a class="permalink" href="perlguts.html#AUTHORS">#</a>AUTHORS</h1>

<p>Until May 1997, this document was maintained by Jeff Okamoto &lt;okamoto@corp.hp.com&gt;. It is now maintained as part of Perl itself by the Perl 5 Porters &lt;perl5-porters@perl.org&gt;.</p>

<p>With lots of help and suggestions from Dean Roehrich, Malcolm Beattie, Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer, Stephen McCamant, and Gurusamy Sarathy.</p>

<h1 id="SEE-ALSO"><a class="permalink" href="perlguts.html#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1>

<p><a href="perlapi.html">perlapi</a>, <a href="perlintern.html">perlintern</a>, <a href="perlxs.html">perlxs</a>, <a href="perlembed.html">perlembed</a></p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
